You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/25 19:54:34 UTC
(maka) 03/05: feat(tui): scale plugin views by owned resources
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 3937a3ebf6b156bcf28e4ac7aa5887f9c870e6e4
Author: M4n5ter <m4...@gmail.com>
AuthorDate: Sat Sep 26 02:40:49 2026 +0800
feat(tui): scale plugin views by owned resources
Remove plugin, page, reader and document inventory quotas. Separate idle subscriptions and background tasks from ordinary calls, and preserve bounded writer backpressure and exact cleanup ownership.
Share transcript updates and account retained history and drafts by bytes. Reserve unsettled results and invalidate draft admission when deferred native drawing changes saved reading state.
Keep trusted VM initialization outside the script watchdog, preserving the 200 ms script budget and original VM failure diagnostics. Add concurrency, cancellation and memory pressure regressions.
Generated-by: Codex
---
crates/cli/tests/fixtures/memory-plugin/host.mjs | 3 +
.../integration/tui/memory_acceptance/capacity.rs | 117 ++++++---
.../integration/tui/memory_acceptance/report.rs | 1 +
crates/client/src/connection.rs | 266 ++++++++++++++++++---
crates/client/src/plugin.rs | 7 +-
crates/client/src/presentation.rs | 38 +++
crates/client/tests/integration/plugin.rs | 49 ++++
crates/js-runtime/src/plugin.rs | 155 ++++++++----
crates/js-runtime/src/plugin/pool.rs | 72 ++++--
crates/js-runtime/src/plugin/sdk.js | 80 ++++++-
crates/js-runtime/src/plugin/worker.rs | 31 ++-
crates/js-runtime/tests/integration/plugin_vm.rs | 12 +-
.../tests/integration/plugin_vm/inventory.rs | 180 ++++++++++++++
crates/plugins/src/terminal_ui/view.rs | 5 -
crates/protocol/src/lib.rs | 2 +-
crates/runtime-host/src/plugins/javascript.rs | 12 +-
.../src/plugins/javascript/invocation.rs | 20 +-
.../src/plugins/javascript/invocation/tests.rs | 192 +++++++++++++++
.../src/plugins/javascript/presenter.rs | 73 +++---
.../src/plugins/javascript/presenter/tests.rs | 83 ++++++-
.../plugins/javascript/registration/terminal.rs | 2 +-
.../runtime-host/src/plugins/javascript/remote.rs | 9 +-
.../src/plugins/javascript/remote/tests.rs | 162 +++++++++++++
.../src/plugins/javascript/remote/tests/fixture.rs | 154 ++++++++++++
.../plugins/javascript/remote/tests/retention.rs | 255 ++++++++++++++++++++
crates/runtime-host/src/server/connection.rs | 41 ++--
.../src/server/plugin_remote/registry.rs | 28 ++-
.../src/server/plugin_remote/worker.rs | 21 +-
.../tests/integration/plugin_remote.rs | 1 +
.../tests/integration/plugin_remote/fixture.rs | 10 +
.../integration/plugin_remote/observations.rs | 137 +++++++++++
.../plugin_remote/observations/finite.rs | 142 +++++++++++
.../tests/integration/plugin_remote/presenter.rs | 1 +
.../plugin_remote/presenter/capacity.rs | 232 ++++++++++++++++++
.../integration/plugin_remote/presenter/sources.rs | 31 ++-
crates/tui/locales/en.ftl | 1 -
crates/tui/locales/zh-CN.ftl | 1 -
crates/tui/locales/zh-TW.ftl | 1 -
crates/tui/src/app.rs | 14 +-
crates/tui/src/apps.rs | 28 ++-
crates/tui/src/apps/admission.rs | 73 +++++-
crates/tui/src/apps/admission/tests.rs | 70 ++++--
crates/tui/src/apps/drafts.rs | 11 +-
crates/tui/src/apps/drafts/admission.rs | 19 +-
crates/tui/src/apps/io/transcript.rs | 16 +-
crates/tui/src/apps/io/transcript/runner.rs | 3 -
crates/tui/src/apps/mount.rs | 3 +-
crates/tui/src/apps/region.rs | 3 +
crates/tui/src/apps/saved/admission.rs | 13 +
crates/tui/src/apps/transcript/runtime.rs | 2 -
crates/tui/src/apps/transcript/tests.rs | 2 +
crates/tui/src/apps/transcript/tests/capacity.rs | 177 ++++++++++++++
crates/tui/src/apps/tree.rs | 2 +-
crates/tui/src/lib.rs | 85 ++++---
crates/tui/src/pages/chat.rs | 8 +
crates/tui/src/state.rs | 127 +++++-----
crates/tui/src/state/snapshot.rs | 32 ++-
crates/tui/src/state/snapshot/admission.rs | 161 +++++++++++--
crates/tui/src/state/snapshot/admission/pages.rs | 8 +-
crates/tui/src/state/snapshot/admission/tests.rs | 131 +++++++++-
.../src/state/snapshot/admission/tests/native.rs | 201 ++++++++++++++++
crates/tui/src/state/store.rs | 2 +-
crates/tui/src/ui/transcript.rs | 43 +++-
crates/tui/src/ui/transcript/groups.rs | 11 +-
crates/tui/src/ui/transcript/search.rs | 6 +-
crates/tui/src/view/session.rs | 4 +
packages/plugin-sdk/README.md | 4 +-
packages/plugin-sdk/README.zh-CN.md | 4 +-
packages/plugin-sdk/src/terminal-transcript.ts | 4 +-
.../plugin-sdk/tests/terminal-capacity.test.mjs | 255 ++++++++++++++++++++
.../tests/terminal-transcript-harness.mjs | 17 +-
packages/runtime-host/src/protocol/index.ts | 2 +-
72 files changed, 3677 insertions(+), 491 deletions(-)
diff --git a/crates/cli/tests/fixtures/memory-plugin/host.mjs b/crates/cli/tests/fixtures/memory-plugin/host.mjs
index 6ee1208edc..7ae2055a85 100644
--- a/crates/cli/tests/fixtures/memory-plugin/host.mjs
+++ b/crates/cli/tests/fixtures/memory-plugin/host.mjs
@@ -58,6 +58,8 @@ export default async function activate(ctx) {
const initialSourceBytes = encoder.encode(JSON.stringify(blocks)).length;
const source = await ctx.tui.transcriptResource('memory-lines', { blocks });
ctx.effect(() => source.close());
+ const changed = await ctx.tui.changes('memory-changed');
+ ctx.effect(() => changed.close());
let viewReads = 0;
let appends = 0;
let appendedBytes = 0;
@@ -106,6 +108,7 @@ export default async function activate(ctx) {
translations: { 'zh-CN': '内存测量', 'zh-TW': '記憶體測量' },
},
context: 'application',
+ changes: 'memory-changed',
icon: { glyph: '▤', ascii: 'M' },
},
);
diff --git a/crates/cli/tests/integration/tui/memory_acceptance/capacity.rs b/crates/cli/tests/integration/tui/memory_acceptance/capacity.rs
index 727253d4f4..2ec9de48d3 100644
--- a/crates/cli/tests/integration/tui/memory_acceptance/capacity.rs
+++ b/crates/cli/tests/integration/tui/memory_acceptance/capacity.rs
@@ -28,41 +28,55 @@ pub(super) fn measure(
log: &mut report::Report,
phase: &'static str,
) {
- let (client, pump) = runtime.block_on(proxy::connect(root));
+ // Exercise many real pages and idle subscriptions on one connection.
+ // These are sample sizes, not product admission limits.
+ let connections = [runtime.block_on(proxy::connect(root))];
+ const PAGES: usize = 64;
let mut documents = Vec::new();
+ let mut waits = Vec::new();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
- let target = runtime.block_on(case::target(&client, "memory"));
- for count in 1..=4 {
+ for count in 1..=PAGES {
+ let index = (count - 1) % connections.len();
+ let client = &connections[index].0;
+ let target = runtime.block_on(case::target(client, "memory"));
sampler.mark(phase, count);
- let document = runtime.block_on(case::document(&client));
- documents.push(document);
- let result = runtime.block_on(read(&client, &target, document)).unwrap();
+ let document = runtime.block_on(case::document(client));
+ documents.push((index, document));
+ let result = runtime.block_on(read(client, &target, document)).unwrap();
assert!(matches!(result, RemoteResult::Value { ref value } if value["kind"] == "view"));
- let records = runtime.block_on(resource(&client, document));
- let stats = runtime.block_on(case::stats(&client));
+ let changed = runtime.block_on(changes(client, document));
+ let (records, reader) = runtime.block_on(resource(client, document));
+ for stream in [changed, reader] {
+ let client = client.clone();
+ waits.push(runtime.spawn(async move {
+ client
+ .plugin_remote(RemoteRequest::Next { document, stream })
+ .await
+ }));
+ }
+ let stats = runtime.block_on(case::stats(client));
assert_eq!(stats["active"], count);
assert_eq!(stats["activations"], 1);
sampler.mark(phase, count);
log.emit(
json!({"kind":"page_capacity","phase":phase,"page_documents":count,
- "document":document,"loaded_resource_records":records,"stats":stats,
+ "document":document,"connection_index":index,"streams_per_page":2,
+ "loaded_resource_records":records,"stats":stats,
"app_reply_payload_bytes":serde_json::to_vec(&result).unwrap().len()}),
);
}
- let fifth = runtime.block_on(case::document(&client));
- documents.push(fifth);
- let denied = runtime.block_on(read(&client, &target, fifth));
+ let client = &connections[0].0;
+ let started = Instant::now();
+ let stats = runtime.block_on(async {
+ tokio::time::timeout(Duration::from_secs(5), case::stats(client))
+ .await
+ .expect("idle subscriptions starved an ordinary business call")
+ });
log.emit(
- json!({"kind":"page_capacity_rejection","phase":phase,"page_documents":4,
- "attempted":5,"result":format!("{denied:?}")}),
- );
- assert!(
- matches!(denied,
- Err(maka_client::RequestFailure::Rejected(maka_client::ClientError::Rejected(ref error)))
- if error.code == maka_protocol::OperationErrorCode::OperationUnavailable
- && error.message.contains("capacity")),
- "fifth page was not rejected for capacity: {denied:?}"
+ json!({"kind":"page_capacity_business_call","phase":phase,"page_documents":PAGES,
+ "idle_waits_dispatched":waits.len(),"duration_ns":started.elapsed().as_nanos(),"stats":stats}),
);
+ assert_eq!(stats["active"], PAGES);
}));
sampler.mark(
if phase == "capacity_before" {
@@ -70,23 +84,33 @@ pub(super) fn measure(
} else {
"capacity_after_closing"
},
- 4,
+ PAGES,
);
let mut cleanup_ok = true;
- for document in documents {
+ for (index, document) in documents {
+ let client = &connections[index].0;
let closed =
runtime.block_on(client.plugin_remote(RemoteRequest::CloseDocument { document }));
log.emit(json!({"kind":"page_capacity_close","phase":phase,"document":document,"result":format!("{closed:?}")}));
cleanup_ok &= matches!(closed, Ok(RemoteResult::Closed));
}
+ runtime.block_on(async {
+ for wait in waits {
+ let result = tokio::time::timeout(Duration::from_secs(5), wait)
+ .await
+ .expect("closed page left an observation wait alive")
+ .unwrap();
+ log.emit(json!({"kind":"page_capacity_wait_closed","phase":phase,"result":format!("{result:?}")}));
+ }
+ });
+ let client = &connections[0].0;
let cleanup = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
assert!(cleanup_ok, "one or more exact page documents did not close");
- let stats = runtime.block_on(case::closed(&client));
+ let stats = runtime.block_on(case::closed(client));
sampler.mark(phase, 0);
log.emit(json!({"kind":"page_capacity_released","phase":phase,"stats":stats}));
}));
- // A new exact document must reuse a released page VM permit without a new
- // backend activation. This is admission evidence, not an RSS threshold.
+ // A new document creates fresh UI state without a new business activation.
let reuse = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if result.is_ok() && cleanup.is_ok() {
sampler.mark(
@@ -97,21 +121,23 @@ pub(super) fn measure(
},
1,
);
- let target = runtime.block_on(case::target(&client, "memory"));
- let document = runtime.block_on(case::document(&client));
- let reopened = runtime.block_on(read(&client, &target, document));
+ let target = runtime.block_on(case::target(client, "memory"));
+ let document = runtime.block_on(case::document(client));
+ let reopened = runtime.block_on(read(client, &target, document));
let close =
runtime.block_on(client.plugin_remote(RemoteRequest::CloseDocument { document }));
log.emit(json!({"kind":"page_capacity_reusable","phase":phase,"read":format!("{reopened:?}"),"close":format!("{close:?}")}));
assert!(reopened.is_ok() && matches!(close, Ok(RemoteResult::Closed)));
- assert_eq!(runtime.block_on(case::stats(&client))["activations"], 1);
+ assert_eq!(runtime.block_on(case::stats(client))["activations"], 1);
}
}));
- client.disconnect();
- runtime.block_on(async {
- client.closed().await;
- pump.await.unwrap();
- });
+ for (client, pump) in connections {
+ client.disconnect();
+ runtime.block_on(async {
+ client.closed().await;
+ pump.await.unwrap();
+ });
+ }
if let Err(error) = result {
std::panic::resume_unwind(error);
}
@@ -123,6 +149,23 @@ pub(super) fn measure(
}
}
+async fn changes(client: &Client, document: Uuid) -> Uuid {
+ let target = case::target(client, "memory-changed").await;
+ let opened = client
+ .plugin_remote(RemoteRequest::Open {
+ binding: case::binding("memory-changed"),
+ target,
+ document,
+ input: json!({"kind":"watch","route":null,"locale":"en"}),
+ })
+ .await
+ .unwrap();
+ let RemoteResult::Opened { stream } = opened else {
+ panic!("expected changes stream: {opened:?}")
+ };
+ stream
+}
+
async fn read(
client: &Client,
target: &Target,
@@ -137,7 +180,7 @@ async fn read(
})
.await
}
-async fn resource(client: &Client, document: Uuid) -> usize {
+async fn resource(client: &Client, document: Uuid) -> (usize, Uuid) {
tokio::time::timeout(Duration::from_secs(5), async {
let mount = Uuid::new_v4();
let target = case::target(client, "memory-lines.stream").await;
@@ -213,7 +256,7 @@ async fn resource(client: &Client, document: Uuid) -> usize {
match page.continuation {
None => {
assert_eq!(records, 256);
- return records;
+ return (records, stream);
}
Some(cursor) => {
assert!(seen.insert(cursor.clone()));
diff --git a/crates/cli/tests/integration/tui/memory_acceptance/report.rs b/crates/cli/tests/integration/tui/memory_acceptance/report.rs
index c1d32c706b..e8726f00ce 100644
--- a/crates/cli/tests/integration/tui/memory_acceptance/report.rs
+++ b/crates/cli/tests/integration/tui/memory_acceptance/report.rs
@@ -64,6 +64,7 @@ impl Report {
"initial_source":{"blocks":1000,"logical_lines_per_block":10,"logical_lines":10000},
"cycles_per_viewport":if smoke {2} else {100},"appends_per_cycle":3,
"reopen_rounds_per_viewport":if smoke {2} else {10},
+ "page_capacity":{"sample_pages":64,"connections":1,"streams_per_page":2},
"sampler_period_ms":10,"clock":"Instant ns from each case origin; actual sample timestamps retained",
"rss_scope":"Host process includes business source and page VMs; TUI process includes kernel/cache; observer excluded",
"wire_scope":"zero-delay proxy observes TUI and capacity probe clients; independent append/stats control client is excluded",
diff --git a/crates/client/src/connection.rs b/crates/client/src/connection.rs
index 86e2658977..427dd46e88 100644
--- a/crates/client/src/connection.rs
+++ b/crates/client/src/connection.rs
@@ -68,10 +68,28 @@ pub enum RequestFailure {
Rejected(ClientError),
}
+enum Admission {
+ Ordinary,
+ Control,
+ Observation,
+}
+impl Admission {
+ fn operation(operation: Operation) -> Self {
+ if matches!(
+ operation,
+ Operation::SubscriptionReady | Operation::SubscriptionClose
+ ) {
+ Self::Control
+ } else {
+ Self::Ordinary
+ }
+ }
+}
+
struct Command {
request: Request,
reply: oneshot::Sender<Result<Value, ClientError>>,
- permit: OwnedSemaphorePermit,
+ permit: Option<OwnedSemaphorePermit>,
presentation: Option<mpsc::Sender<OAuthPresentation>>,
}
@@ -96,7 +114,7 @@ struct Pending {
operation: Operation,
observation: PendingObservation,
reply: oneshot::Sender<Result<Value, ClientError>>,
- _permit: OwnedSemaphorePermit,
+ _permit: Option<OwnedSemaphorePermit>,
presentation: Option<String>,
}
@@ -216,6 +234,8 @@ impl Client {
let mut pending = HashMap::<String, Pending>::new();
let mut subscriptions = Subscriptions::default();
let mut presentation = Presentation::default();
+ let mut queued_command: Option<Command> = None;
+ let mut control_frame: Option<Value> = None;
let failure = loop {
let presentation_consumer = presentation.consumer();
tokio::select! {
@@ -227,10 +247,8 @@ impl Client {
None => std::future::pending().await,
}
} => break closed("OAuth presentation consumer dropped"),
- frame = presentation.completion() => {
- if outbound.try_send(frame).is_err() {
- break closed("Host writer unavailable");
- }
+ frame = presentation.completion(), if control_frame.is_none() => {
+ control_frame = Some(frame);
},
result = &mut writer_task => break match result {
Ok(Err(error)) => error,
@@ -246,14 +264,16 @@ impl Client {
if value.get("kind").and_then(Value::as_str)
.is_some_and(maka_protocol::capability::is_host_frame_kind)
{
- match presentation.frame(&value) {
- Ok(Some(frame)) => {
- if outbound.try_send(frame).is_err() {
- break closed("Host writer unavailable");
- }
- }
- Ok(None) => {}
+ let produced = match presentation.frame(&value) {
+ Ok(produced) => produced,
Err(error) => break error,
+ };
+ if control_frame.as_ref().is_some_and(|frame| !presentation.current_control(frame)) {
+ control_frame = None;
+ }
+ if let Some(frame) = produced
+ && control_frame.replace(frame).is_some() {
+ break protocol("Host presentation exceeded pending control flow");
}
continue;
}
@@ -310,8 +330,20 @@ impl Client {
}
}
}
- command = commands_rx.recv() => {
+ command = commands_rx.recv(), if queued_command.is_none() => {
let Some(command) = command else { break closed("client disconnected"); };
+ queued_command = Some(command);
+ }
+ ready = outbound.reserve(), if control_frame.is_some() || queued_command.is_some() => {
+ let permit = match ready {
+ Ok(permit) => permit,
+ Err(_) => break closed("Host writer unavailable"),
+ };
+ if let Some(frame) = control_frame.take() {
+ permit.send(frame);
+ continue;
+ }
+ let command = queued_command.take().expect("pending outbound command");
if command.reply.is_closed() {
continue;
}
@@ -340,17 +372,18 @@ impl Client {
_permit: command.permit,
presentation: registration,
});
- // Admission is smaller than this queue, so overflow
- // indicates a broken invariant, not ordinary backpressure.
- if outbound.try_send(serde_json::to_value(command.request).expect("wire request")).is_err() {
- break closed("Host writer unavailable");
- }
+ // Only a writer reservation admits this frame. While
+ // waiting, the same select continues draining replies.
+ permit.send(serde_json::to_value(command.request).expect("wire request"));
}
}
};
cancel.cancel();
writer_task.abort();
commands_rx.close();
+ if let Some(command) = queued_command {
+ let _ = command.reply.send(Err(failure.clone()));
+ }
for (_, waiter) in pending {
let _ = waiter.reply.send(Err(failure.clone()));
}
@@ -377,7 +410,14 @@ impl Client {
input: Value,
timeout: Duration,
) -> Result<Value, RequestFailure> {
- self.request_inner(operation, input, timeout, None).await
+ self.request_inner(
+ operation,
+ input,
+ timeout,
+ None,
+ Admission::operation(operation),
+ )
+ .await
}
pub(crate) async fn request_presentation(
@@ -390,6 +430,29 @@ impl Client {
input,
REQUEST_TIMEOUT,
Some(sender),
+ Admission::Ordinary,
+ )
+ .await
+ }
+
+ /// Typed stream waits consume owned observation lifetimes, not finite RPC
+ /// slots. Raw requests cannot select this admission path.
+ pub(crate) async fn request_remote(
+ &self,
+ input: &maka_protocol::plugin::RemoteRequest,
+ ) -> Result<Value, RequestFailure> {
+ use maka_protocol::plugin::RemoteRequest;
+ let admission = match input {
+ RemoteRequest::Next { .. } => Admission::Observation,
+ RemoteRequest::Close { .. } | RemoteRequest::CloseDocument { .. } => Admission::Control,
+ _ => Admission::Ordinary,
+ };
+ self.request_inner(
+ Operation::PluginRemote,
+ serde_json::to_value(input).expect("wire input"),
+ REQUEST_TIMEOUT,
+ None,
+ admission,
)
.await
}
@@ -400,10 +463,11 @@ impl Client {
input: Value,
timeout: Duration,
presentation: Option<mpsc::Sender<OAuthPresentation>>,
+ admission: Admission,
) -> Result<Value, RequestFailure> {
let deadline = tokio::time::Instant::now() + timeout;
let pending = self
- .enqueue(operation, input, deadline, presentation)
+ .enqueue(operation, input, deadline, presentation, admission)
.await?;
tokio::time::timeout_at(deadline, pending.settle())
.await
@@ -420,6 +484,7 @@ impl Client {
input,
tokio::time::Instant::now() + REQUEST_TIMEOUT,
None,
+ Admission::operation(operation),
)
.await
}
@@ -430,6 +495,7 @@ impl Client {
input: Value,
deadline: tokio::time::Instant,
presentation: Option<mpsc::Sender<OAuthPresentation>>,
+ admission: Admission,
) -> Result<PendingRequest, RequestFailure> {
if operation == Operation::ClientCapabilityReplace && presentation.is_none() {
return Err(RequestFailure::NotDispatched(protocol(
@@ -442,15 +508,15 @@ impl Client {
.map_err(|error| RequestFailure::NotDispatched(protocol(error)))?;
// Waiting for both admission and queue space is cancellable and bounded.
let admitted = tokio::time::timeout_at(deadline, async {
- let capacity = if matches!(
- operation,
- Operation::SubscriptionReady | Operation::SubscriptionClose
- ) {
- &self.control_capacity
- } else {
- &self.capacity
+ let capacity = match admission {
+ Admission::Ordinary => Some(&self.capacity),
+ Admission::Control => Some(&self.control_capacity),
+ Admission::Observation => None,
+ };
+ let permit = match capacity {
+ Some(capacity) => Some(capacity.clone().acquire_owned().await.map_err(closed)?),
+ None => None,
};
- let permit = capacity.clone().acquire_owned().await.map_err(closed)?;
let queue = self.commands.reserve().await.map_err(closed)?;
Ok::<_, ClientError>((permit, queue))
})
@@ -540,3 +606,145 @@ mod receipt_tests {
));
}
}
+
+#[cfg(test)]
+mod observation_tests {
+ use super::*;
+ use std::{
+ pin::Pin,
+ sync::{
+ Mutex,
+ atomic::{AtomicBool, Ordering},
+ },
+ task::{Context, Poll, Waker},
+ };
+ use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
+
+ const ROOT: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+
+ #[derive(Default)]
+ struct Gate {
+ blocked: AtomicBool,
+ entered: tokio::sync::Notify,
+ writer: Mutex<Option<Waker>>,
+ }
+ struct HeldWriter {
+ stream: DuplexStream,
+ gate: Arc<Gate>,
+ }
+ impl AsyncRead for HeldWriter {
+ fn poll_read(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ buf: &mut ReadBuf<'_>,
+ ) -> Poll<std::io::Result<()>> {
+ Pin::new(&mut self.stream).poll_read(cx, buf)
+ }
+ }
+ impl AsyncWrite for HeldWriter {
+ fn poll_write(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<std::io::Result<usize>> {
+ if self.gate.blocked.load(Ordering::Acquire) {
+ *self.gate.writer.lock().unwrap() = Some(cx.waker().clone());
+ self.gate.entered.notify_one();
+ if self.gate.blocked.load(Ordering::Acquire) {
+ return Poll::Pending;
+ }
+ }
+ Pin::new(&mut self.stream).poll_write(cx, bytes)
+ }
+ fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
+ Pin::new(&mut self.stream).poll_flush(cx)
+ }
+ fn poll_shutdown(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<std::io::Result<()>> {
+ Pin::new(&mut self.stream).poll_shutdown(cx)
+ }
+ }
+
+ #[tokio::test]
+ async fn saturated_observation_writer_keeps_reading_replies_and_notifications() {
+ tokio::time::timeout(Duration::from_secs(3), async {
+ use serde_json::json;
+ let (local, remote) = tokio::io::duplex(4096);
+ let gate = Arc::new(Gate::default());
+ let (mut reader, mut writer) = maka_transport::ndjson::split(remote, CancellationToken::new());
+ let server = tokio::spawn(async move {
+ reader.read().await.unwrap().unwrap();
+ writer.write(&json!({"kind":"accepted","rootId":ROOT,"hostEpoch":"epoch","connectionId":"test", "selectedProtocol":PROTOCOL_VERSION,"compatibilityEpoch":COMPATIBILITY_EPOCH,"compositionId":COMPOSITION_ID,"compositionRevision":"test","state":"ready"})).await.unwrap();
+ (reader, writer)
+ });
+ let (client, mut notices) = Client::connect(HeldWriter { stream: local, gate: gate.clone() }, ROOT, "epoch", crate::Operations).await.unwrap();
+ let (mut reader, mut writer) = server.await.unwrap();
+ let publishing = tokio::spawn({
+ let client = client.clone();
+ async move { client.publish_oauth_presentation().await }
+ });
+ let registration = reader.read().await.unwrap().unwrap();
+ writer.write(&json!({"requestId":registration["requestId"],"operation":registration["operation"],"ok":true,
+ "result":{"registrationId":registration["input"]["registrationId"],"revision":1}})).await.unwrap();
+ let mut service = publishing.await.unwrap().unwrap();
+ let registration_id = service.registration_id.clone();
+ let call = |id: &str| json!({"kind":"client.capability.service_call","registrationId":registration_id,
+ "invocationId":id,"serviceId":"oauth_presentation","version":"1","method":"open_external",
+ "input":{"url":"https://login.example/device","stateHint":id}});
+ let finite = client.request_pending(Operation::HostWake, json!({})).await.unwrap();
+ let original = reader.read().await.unwrap().unwrap();
+ gate.blocked.store(true, Ordering::Release);
+ let mut waiting = Vec::new();
+ // One active write, the bounded outbound channel, one staged
+ // command and the bounded producer channel are now all occupied.
+ let count = 1 + MAX_IN_FLIGHT_DOMAIN_REQUESTS + 2 + 1 + QUEUE_CAPACITY;
+ for _ in 0..count {
+ waiting.push(client.enqueue(Operation::PluginRemote,
+ json!({"kind":"next","document":uuid::Uuid::new_v4(),"stream":uuid::Uuid::new_v4()}),
+ tokio::time::Instant::now() + REQUEST_TIMEOUT, None, Admission::Observation).await.unwrap());
+ }
+ gate.entered.notified().await;
+ assert_eq!(client.commands.capacity(), 0);
+ writer.write(&json!({"requestId":original["requestId"],"operation":"host.wake","ok":true,"result":{}})).await.unwrap();
+ writer.write(&json!({"kind":"configuration.changed","revision":7})).await.unwrap();
+ assert_eq!(finite.settle().await.unwrap(), json!({}));
+ assert!(matches!(notices.recv().await, Some(Notification::Catalog(notice)) if notice.revision == 7));
+ assert_eq!(client.capacity.available_permits(), MAX_IN_FLIGHT_DOMAIN_REQUESTS - 4);
+ writer.write(&call("original")).await.unwrap();
+ writer.write(&json!({"kind":"configuration.changed","revision":8})).await.unwrap();
+ assert!(matches!(notices.recv().await, Some(Notification::Catalog(notice)) if notice.revision == 8));
+ // A's accepted frame is now staged behind the full writer. A
+ // cancellation/release allows B without making A's frame B's own.
+ writer.write(&json!({"kind":"client.capability.cancel","invocationId":"original"})).await.unwrap();
+ writer.write(&json!({"kind":"client.capability.release","invocationId":"original"})).await.unwrap();
+ writer.write(&call("replacement")).await.unwrap();
+ writer.write(&json!({"kind":"configuration.changed","revision":9})).await.unwrap();
+ assert!(matches!(notices.recv().await, Some(Notification::Catalog(notice)) if notice.revision == 9));
+ gate.blocked.store(false, Ordering::Release);
+ if let Some(waker) = gate.writer.lock().unwrap().take() { waker.wake(); }
+ let mut accepted = 0;
+ for _ in 0..count + 1 {
+ let frame = reader.read().await.unwrap().unwrap();
+ if frame.get("kind").is_some() {
+ assert_eq!(frame["kind"], "client.capability.accepted");
+ assert_eq!(frame["invocationId"], "replacement", "cancelled A must never leave staging");
+ accepted += 1;
+ } else {
+ writer.write(&json!({"requestId":frame["requestId"],"operation":"plugin.remote","ok":true,"result":{"kind":"end"}})).await.unwrap();
+ }
+ }
+ assert_eq!(accepted, 1);
+ for pending in waiting { assert_eq!(pending.settle().await.unwrap(), json!({"kind":"end"})); }
+ writer.write(&json!({"kind":"client.capability.admitted","invocationId":"replacement"})).await.unwrap();
+ let shown = service.recv().await.unwrap();
+ assert_eq!(shown.state_hint.as_deref(), Some("replacement"));
+ assert!(shown.acknowledge_presented());
+ let result = reader.read().await.unwrap().unwrap();
+ assert_eq!(result["kind"], "client.capability.result");
+ assert_eq!(result["invocationId"], "replacement");
+ client.disconnect();
+ }).await.expect("writer backpressure blocked the independent reader");
+ }
+}
diff --git a/crates/client/src/plugin.rs b/crates/client/src/plugin.rs
index 3e4d93229f..7c467694b9 100644
--- a/crates/client/src/plugin.rs
+++ b/crates/client/src/plugin.rs
@@ -149,12 +149,7 @@ impl Client {
&self,
input: RemoteRequest,
) -> Result<RemoteResult, RequestFailure> {
- let value = self
- .request(
- Operation::PluginRemote,
- serde_json::to_value(&input).expect("wire input"),
- )
- .await?;
+ let value = self.request_remote(&input).await?;
let result: RemoteResult = serde_json::from_value(value)
.map_err(|error| self.invalid_plugin_result(error.to_string()))?;
let valid = matches!(
diff --git a/crates/client/src/presentation.rs b/crates/client/src/presentation.rs
index b17d522309..78db442dab 100644
--- a/crates/client/src/presentation.rs
+++ b/crates/client/src/presentation.rs
@@ -174,6 +174,15 @@ impl Presentation {
.map(|registration| registration.sender.clone())
}
+ /// A control frame not yet handed to the writer belongs only to the
+ /// still-live invocation that produced it. Cancellation never retargets it.
+ pub fn current_control(&self, frame: &Value) -> bool {
+ self.invocation.as_ref().is_some_and(|invocation| {
+ frame.get("invocationId").and_then(Value::as_str) == Some(invocation.id.as_str())
+ && !invocation.cancelled.is_cancelled()
+ })
+ }
+
pub async fn completion(&mut self) -> Value {
let Some(Invocation {
id,
@@ -322,3 +331,32 @@ fn trusted_url(value: &str) -> Option<String> {
&& url.password().is_none())
.then(|| url.into())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cancellation_and_release_retire_only_their_staged_invocation_controls() {
+ for retirement in [
+ json!({"kind":"client.capability.cancel","invocationId":"original"}),
+ json!({"kind":"client.capability.release","invocationId":"original"}),
+ json!({"kind":"client.capability.registration_release","registrationId":"registration"}),
+ ] {
+ let mut presentation = Presentation::default();
+ let (sender, _receiver) = mpsc::channel(1);
+ presentation.prepare(&json!({"registrationId":"registration","offers":[],"services":[{
+ "serviceId":oauth::PRESENTATION_SERVICE_ID,"version":oauth::PRESENTATION_SERVICE_VERSION
+ }]}), sender).unwrap();
+ let accepted = presentation.frame(&json!({"kind":"client.capability.service_call",
+ "registrationId":"registration","invocationId":"original",
+ "serviceId":oauth::PRESENTATION_SERVICE_ID,"version":oauth::PRESENTATION_SERVICE_VERSION,
+ "method":"open_external","input":{"url":"https://login.example/device"}
+ })).unwrap().unwrap();
+ assert!(presentation.current_control(&accepted));
+ assert!(!presentation.current_control(&json!({"invocationId":"another"})));
+ assert!(presentation.frame(&retirement).unwrap().is_none());
+ assert!(!presentation.current_control(&accepted));
+ }
+ }
+}
diff --git a/crates/client/tests/integration/plugin.rs b/crates/client/tests/integration/plugin.rs
index 2c36efff01..1da6eb3104 100644
--- a/crates/client/tests/integration/plugin.rs
+++ b/crates/client/tests/integration/plugin.rs
@@ -341,3 +341,52 @@ async fn management_requests_cross_the_client_registry_with_review_preconditions
);
client.disconnect();
}
+
+#[tokio::test]
+async fn idle_remote_waits_leave_finite_calls_and_control_close_admissible() {
+ tokio::time::timeout(Duration::from_secs(3), async {
+ let (client, _notices, mut reader, mut writer) = pair_with(maka_client::Operations).await;
+ let document = uuid::Uuid::new_v4();
+ let mut waiting = Vec::new();
+ let mut frames = Vec::new();
+ for _ in 0..96 {
+ let client = client.clone();
+ waiting.push(tokio::spawn(async move {
+ client.plugin_remote(RemoteRequest::Next { document, stream: uuid::Uuid::new_v4() }).await
+ }));
+ }
+ for _ in 0..96 {
+ let frame = reader.read().await.unwrap().unwrap();
+ assert_eq!(frame["input"]["kind"], "next");
+ frames.push(frame);
+ }
+ // Saturate only the unchanged ordinary budget. Close still owns a
+ // reserved control permit, regardless of the idle observation count.
+ let mut calls = Vec::new();
+ for _ in 0..60 {
+ let client = client.clone();
+ calls.push(tokio::spawn(async move {
+ client.request(maka_protocol::Operation::HostWake, json!({})).await
+ }));
+ }
+ let mut call_frames = Vec::new();
+ for _ in 0..60 { call_frames.push(reader.read().await.unwrap().unwrap()); }
+ let close = tokio::spawn({
+ let client = client.clone();
+ async move { client.plugin_remote(RemoteRequest::CloseDocument { document }).await }
+ });
+ let frame = reader.read().await.unwrap().unwrap();
+ assert_eq!(frame["input"]["kind"], "close_document");
+ writer.write(&json!({"requestId":frame["requestId"],"operation":"plugin.remote","ok":true,"result":{"kind":"closed"}})).await.unwrap();
+ assert!(close.await.unwrap().is_ok());
+ for frame in call_frames {
+ writer.write(&json!({"requestId":frame["requestId"],"operation":frame["operation"],"ok":true,"result":{}})).await.unwrap();
+ }
+ for call in calls { assert!(call.await.unwrap().is_ok()); }
+ for frame in frames {
+ writer.write(&json!({"requestId":frame["requestId"],"operation":"plugin.remote","ok":true,"result":{"kind":"end"}})).await.unwrap();
+ }
+ for wait in waiting { assert!(wait.await.unwrap().is_ok()); }
+ client.disconnect();
+ }).await.expect("idle observations blocked finite/control requests");
+}
diff --git a/crates/js-runtime/src/plugin.rs b/crates/js-runtime/src/plugin.rs
index 225b34190a..02b6c8a45f 100644
--- a/crates/js-runtime/src/plugin.rs
+++ b/crates/js-runtime/src/plugin.rs
@@ -68,7 +68,6 @@ pub struct Vm(Arc<Inner>);
struct Inner {
commands: mpsc::UnboundedSender<Command>,
health: Arc<Health>,
- modules: Arc<Semaphore>,
calls: Arc<Semaphore>,
bytes: Arc<Semaphore>,
sequence: AtomicU64,
@@ -86,6 +85,7 @@ impl WeakModule {
struct ModuleOwner {
vm: Vm,
id: u64,
+ bootstrap: Bootstrap,
closing: AtomicBool,
state: watch::Receiver<State>,
control_calls: Arc<Semaphore>,
@@ -120,7 +120,6 @@ enum Command {
name: String,
source: String,
state: watch::Sender<State>,
- slot: OwnedSemaphorePermit,
bytes: OwnedSemaphorePermit,
},
Call {
@@ -128,7 +127,7 @@ enum Command {
path: Vec<String>,
args: Vec<Value>,
reply: oneshot::Sender<Result<Value>>,
- slot: OwnedSemaphorePermit,
+ slot: Option<OwnedSemaphorePermit>,
bytes: OwnedSemaphorePermit,
},
Close(u64),
@@ -143,23 +142,43 @@ enum Command {
},
}
-#[derive(Clone, Copy)]
+#[derive(Clone, Copy, PartialEq, Eq)]
enum Bootstrap {
Plain,
Plugin,
Presenter,
}
+#[derive(Clone, Copy)]
+enum CallLane {
+ Work,
+ Control,
+ OwnedWait,
+}
+
struct Health {
isolate: OnceLock<v8::IsolateHandle>,
failure: Mutex<Option<Error>>,
stopped: CancellationToken,
closed: CancellationToken,
- polling: watch::Sender<Option<tokio::time::Instant>>,
+ initializing: AtomicBool,
+ polling: watch::Sender<Option<PollClock>>,
+}
+#[derive(Clone, Copy)]
+struct PollClock {
+ started: tokio::time::Instant,
+ initializing: bool,
}
impl Health {
fn fail(&self, error: Error) {
- self.failure.lock().unwrap().get_or_insert(error);
+ self.failure.lock().unwrap().get_or_insert_with(|| {
+ let phase = if self.initializing.load(Ordering::SeqCst) {
+ "runtime initialization"
+ } else {
+ "script poll"
+ };
+ failed(format!("{} (phase: {phase})", error.0))
+ });
self.stopped.cancel();
if let Some(isolate) = self.isolate.get() {
isolate.terminate_execution();
@@ -176,10 +195,6 @@ impl Health {
impl Vm {
pub fn new(limits: Limits) -> Result<Self> {
- Self::start(limits, None)
- }
-
- fn start(limits: Limits, reservation: Option<OwnedSemaphorePermit>) -> Result<Self> {
if limits.heap_bytes < 16 * 1024 * 1024 || limits.synchronous_slice.is_zero() {
return Err(failed("invalid VM limits"));
}
@@ -191,6 +206,7 @@ impl Vm {
failure: Mutex::default(),
stopped: CancellationToken::new(),
closed: CancellationToken::new(),
+ initializing: AtomicBool::new(true),
polling: watch::channel(None).0,
});
let observer = health.clone();
@@ -214,7 +230,6 @@ impl Vm {
Ok(Err(error)) => owner.fail(error),
Err(_) => owner.fail(failed("worker panicked")),
}
- drop(reservation);
owner.closed.cancel();
})
{
@@ -225,7 +240,6 @@ impl Vm {
Ok(Self(Arc::new(Inner {
commands,
health,
- modules: Arc::new(Semaphore::new(64)),
calls: Arc::new(Semaphore::new(128)),
bytes: Arc::new(Semaphore::new(32 * 1024 * 1024)),
sequence: AtomicU64::new(1),
@@ -280,12 +294,6 @@ impl Vm {
{
return Err(failed("module is too large or VM is stopped"));
}
- let slot = self
- .0
- .modules
- .clone()
- .try_acquire_owned()
- .map_err(|_| failed("module capacity exhausted"))?;
let bytes = self
.0
.bytes
@@ -307,13 +315,13 @@ impl Vm {
name,
source,
state,
- slot,
bytes,
})
.map_err(|_| self.0.health.error())?;
Ok(Module(Arc::new(ModuleOwner {
vm: self.clone(),
id,
+ bootstrap,
closing: AtomicBool::new(false),
state: receiver,
control_calls: Arc::new(Semaphore::new(2)),
@@ -368,13 +376,22 @@ impl Module {
pub fn vm_failed(&self) -> bool {
self.0.vm.is_terminated()
}
+ /// First recorded VM stop reason. Cleanup owners inspect this before their
+ /// own intentional shutdown, which may record a normal stop when none exists.
+ pub fn vm_failure(&self) -> Option<Error> {
+ self.0.vm.0.health.failure.lock().unwrap().clone()
+ }
pub async fn cancel_call(&self, id: String) -> Result<()> {
if id.len() > 128 {
return Err(failed("invalid invocation identity"));
}
- self.call_inner(vec!["cancel".into()], vec![Value::String(id)], true)
- .await
- .map(|_| ())
+ self.call_inner(
+ vec!["cancel".into()],
+ vec![Value::String(id)],
+ CallLane::Control,
+ )
+ .await
+ .map(|_| ())
}
/// Routing identity inside this VM, not authorization or a durable identity.
pub fn host_key(&self) -> String {
@@ -399,7 +416,52 @@ impl Module {
/// Function paths are relative to the module namespace, not globalThis.
pub async fn call(&self, path: Vec<String>, args: Vec<Value>) -> Result<Value> {
- self.call_inner(path, args, false).await
+ self.call_inner(path, args, CallLane::Work).await
+ }
+
+ /// Wait only on an SDK-owned stream handle. Idle observations retain their
+ /// argument bytes and module lifetime without occupying ordinary work slots.
+ pub async fn stream_next(&self, handle: &str) -> Result<Value> {
+ self.validate_stream_handle(handle)?;
+ self.call_inner(
+ vec!["streamNext".into()],
+ vec![Value::String(handle.into())],
+ CallLane::OwnedWait,
+ )
+ .await
+ }
+
+ /// Stream cleanup uses reserved control capacity even when work is saturated.
+ pub async fn stream_close(&self, handle: &str) -> Result<()> {
+ self.validate_stream_handle(handle)?;
+ self.call_inner(
+ vec!["streamClose".into()],
+ vec![Value::String(handle.into())],
+ CallLane::Control,
+ )
+ .await
+ .map(|_| ())
+ }
+
+ fn validate_stream_handle(&self, handle: &str) -> Result<()> {
+ if self.0.bootstrap != Bootstrap::Plugin || handle.is_empty() || handle.len() > 128 {
+ return Err(failed(
+ "stream observation requires an SDK plugin stream handle",
+ ));
+ }
+ Ok(())
+ }
+
+ /// Start the SDK's prepared business jobs and await their owned lifetime.
+ /// The SDK admits this transition once; waiting jobs consume neither work
+ /// slots nor the control capacity needed to retire them.
+ pub async fn start_tasks(&self) -> Result<()> {
+ if self.0.bootstrap != Bootstrap::Plugin {
+ return Err(failed("business tasks require an SDK plugin module"));
+ }
+ self.call_inner(vec!["effective".into()], vec![], CallLane::OwnedWait)
+ .await
+ .map(|_| ())
}
/// Reserved control capacity lets retirement signal calls that fill the
@@ -409,7 +471,7 @@ impl Module {
Lifecycle::Retire => "retire",
Lifecycle::Dispose => "dispose",
};
- self.call_inner(vec![name.into()], vec![], true)
+ self.call_inner(vec![name.into()], vec![], CallLane::Control)
.await
.map(|_| ())
}
@@ -423,7 +485,7 @@ impl Module {
&self,
path: Vec<String>,
args: Vec<Value>,
- control: bool,
+ lane: CallLane,
) -> Result<Value> {
self.ready().await?;
if path.is_empty()
@@ -436,30 +498,30 @@ impl Module {
if size > 32 * 1024 * 1024 {
return Err(failed("call arguments exceed 32 MiB"));
}
- let calls = if control {
- &self.0.control_calls
- } else {
- &self.0.vm.0.calls
- };
- let budget = if control {
+ let budget = if matches!(lane, CallLane::Control) {
&self.0.control_bytes
} else {
&self.0.vm.0.bytes
};
- let slot = if control {
+ let slot = match lane {
// Retirement and several stream cancellations may arrive together.
// Wait in the reserved lane instead of rejecting cleanup while its
// other signals are making progress; ordinary calls stay fail-fast.
- tokio::select! {
+ CallLane::Control => Some(tokio::select! {
biased;
_ = self.0.vm.0.health.stopped.cancelled() => return Err(self.0.vm.0.health.error()),
- slot = calls.clone().acquire_owned() => slot.map_err(|_| self.0.vm.0.health.error())?,
- }
- } else {
- calls
- .clone()
- .try_acquire_owned()
- .map_err(|_| failed("VM call capacity exhausted"))?
+ slot = self.0.control_calls.clone().acquire_owned() => slot.map_err(|_| self.0.vm.0.health.error())?,
+ }),
+ CallLane::Work => Some(
+ self.0
+ .vm
+ .0
+ .calls
+ .clone()
+ .try_acquire_owned()
+ .map_err(|_| failed("VM call capacity exhausted"))?,
+ ),
+ CallLane::OwnedWait => None,
};
let bytes = budget
.clone()
@@ -504,15 +566,22 @@ impl Module {
async fn monitor(health: Arc<Health>, slice: Duration) {
let mut polling = health.polling.subscribe();
loop {
- let deadline = polling.borrow_and_update().map(|started| started + slice);
+ let deadline = polling
+ .borrow_and_update()
+ .map(|clock| clock.started + slice);
tokio::select! {
_ = health.closed.cancelled() => return,
_ = polling.changed() => {},
_ = async { if let Some(deadline) = deadline { tokio::time::sleep_until(deadline).await } else { std::future::pending().await } } => {
// Recheck under the watch read lock; the VM may already be idle.
let clock = polling.borrow();
- if clock.is_some_and(|started| started + slice <= tokio::time::Instant::now()) {
- health.fail(failed("synchronous execution budget exceeded"));
+ if let Some(clock) = *clock
+ && clock.started + slice <= tokio::time::Instant::now() {
+ let phase = if clock.initializing { "runtime initialization" } else { "script poll" };
+ health.fail(failed(format!(
+ "synchronous execution budget exceeded (poll began in {phase}, wall elapsed {} ms)",
+ clock.started.elapsed().as_millis(),
+ )));
return;
}
}
diff --git a/crates/js-runtime/src/plugin/pool.rs b/crates/js-runtime/src/plugin/pool.rs
index 75097fc616..8125297797 100644
--- a/crates/js-runtime/src/plugin/pool.rs
+++ b/crates/js-runtime/src/plugin/pool.rs
@@ -22,13 +22,10 @@ use std::{
collections::BTreeMap,
sync::{Arc, Mutex, Weak},
};
-use tokio::sync::Semaphore;
/// Lazy execution placement. Weak references never keep an unused VM alive.
-/// Dedicated capacity is held through worker teardown, not just handle release.
pub struct Pool {
limits: Limits,
- dedicated: Arc<Semaphore>,
state: Mutex<State>,
}
#[derive(Default)]
@@ -37,15 +34,11 @@ struct State {
dedicated: BTreeMap<String, Weak<Inner>>,
}
impl Pool {
- pub fn new(limits: Limits, dedicated_limit: usize) -> Result<Self> {
- if dedicated_limit > 64 {
- return Err(failed("dedicated VM limit exceeds 64"));
- }
- Ok(Self {
+ pub fn new(limits: Limits) -> Self {
+ Self {
limits,
- dedicated: Arc::new(Semaphore::new(dedicated_limit)),
state: Mutex::new(State::default()),
- })
+ }
}
pub fn shared(&self) -> Result<Vm> {
@@ -68,12 +61,7 @@ impl Pool {
return Ok(vm);
}
state.dedicated.retain(|_, vm| vm.strong_count() != 0);
- let reservation = self
- .dedicated
- .clone()
- .try_acquire_owned()
- .map_err(|_| failed("dedicated VM capacity exhausted"))?;
- let vm = Vm::start(self.limits.clone(), Some(reservation))?;
+ let vm = Vm::new(self.limits.clone())?;
state
.dedicated
.insert(generation.into(), Arc::downgrade(&vm.0));
@@ -83,3 +71,55 @@ impl Pool {
fn alive(inner: &Weak<Inner>) -> Option<Vm> {
inner.upgrade().map(Vm).filter(|vm| !vm.is_terminated())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+ use std::time::Duration;
+
+ #[tokio::test]
+ async fn dedicated_generations_are_lazy_weak_and_not_limited_by_inventory_count() {
+ tokio::time::timeout(Duration::from_secs(15), async {
+ let pool = Pool::new(Limits::default());
+ assert!(pool.state.lock().unwrap().dedicated.is_empty());
+ let mut generations = Vec::new();
+ for index in 0..6 {
+ let generation = format!("package-{index}:digest");
+ let vm = pool.dedicated(&generation).unwrap();
+ let module = vm.load(format!("package-{index}.mjs"), format!(
+ "globalThis.loaded = (globalThis.loaded ?? 0) + 1; export function value() {{ return [{index}, globalThis.loaded]; }}"
+ )).unwrap();
+ assert_eq!(module.call(vec!["value".into()], vec![]).await.unwrap(), json!([index, 1]));
+ let repeated = pool.dedicated(&generation).unwrap();
+ assert!(Arc::ptr_eq(&vm.0, &repeated.0));
+ assert_eq!(repeated.statistics(false).await.unwrap().modules, 1);
+ generations.push((generation, vm, module));
+ }
+ assert_eq!(pool.state.lock().unwrap().dedicated.len(), 6);
+ let mut released = Vec::new();
+ for (generation, vm, module) in generations {
+ let weak_module = module.downgrade();
+ module.close().await.unwrap();
+ assert_eq!(vm.statistics(false).await.unwrap().modules, 0);
+ drop(module);
+ assert!(weak_module.upgrade().is_none());
+ let health = vm.0.health.clone();
+ let weak_vm = Arc::downgrade(&vm.0);
+ drop(vm);
+ assert!(weak_vm.upgrade().is_none(), "pool must not own its VMs");
+ health.closed.cancelled().await;
+ released.push((generation, health));
+ }
+ for (generation, old_health) in released {
+ let replacement = pool.dedicated(&generation).unwrap();
+ assert!(!Arc::ptr_eq(&replacement.0.health, &old_health));
+ assert!(!replacement.is_terminated());
+ let module = replacement.load("fresh.mjs".into(), "export function fresh() { return globalThis.loaded === undefined; }".into()).unwrap();
+ assert_eq!(module.call(vec!["fresh".into()], vec![]).await.unwrap(), json!(true));
+ module.close().await.unwrap();
+ replacement.shutdown().await;
+ }
+ }).await.expect("module close and worker teardown acknowledge without sleeps");
+ }
+}
diff --git a/crates/js-runtime/src/plugin/sdk.js b/crates/js-runtime/src/plugin/sdk.js
index e6cc49b829..e791bb46a0 100644
--- a/crates/js-runtime/src/plugin/sdk.js
+++ b/crates/js-runtime/src/plugin/sdk.js
@@ -383,8 +383,10 @@
const sources = new Map();
const timings = new Map();
const mounts = new Map();
+ const retained = new Map();
const counters = { opened: 0, closed: 0, invalidated: 0, pageReads: 0, updates: 0 };
let sourceBytes = 0;
+ let historicalBytes = 0;
let revision = 0;
let mountSequence = 0;
let closed = false;
@@ -393,6 +395,34 @@
};
const bytes = (value) => encoder.encode(value).length;
const encodedSize = (value) => bytes(JSON.stringify(value));
+ const retainCurrent = (value, bytes) => {
+ retained.set(value, { bytes, current: true, snapshots: 0 });
+ };
+ const releaseCurrent = (value) => {
+ const owner = retained.get(value);
+ owner.current = false;
+ if (owner.snapshots) historicalBytes += owner.bytes;
+ else retained.delete(value);
+ };
+ const acquireSnapshot = (value) => {
+ retained.get(value).snapshots++;
+ };
+ const releaseSnapshot = (value) => {
+ const owner = retained.get(value);
+ owner.snapshots--;
+ if (!owner.current && owner.snapshots === 0) {
+ historicalBytes -= owner.bytes;
+ retained.delete(value);
+ }
+ };
+ const boundHistory = () => {
+ // Current records are already validated. Only stale snapshots are evicted;
+ // identity accounting avoids scanning every reader on each streamed token.
+ for (const mount of mounts.values()) {
+ if (sourceBytes + historicalBytes <= SOURCE_BYTES) break;
+ mount.invalidate();
+ }
+ };
const safe = (value, multiline = false) =>
typeof value === 'string' &&
!/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value) &&
@@ -542,6 +572,7 @@
const entry = copyBlock(block);
if (sources.has(entry.key)) fail('Duplicate transcript key');
sources.set(entry.key, entry);
+ retainCurrent(entry, entry.encoded.length);
sourceBytes += entry.encoded.length;
if (sources.size > 4096 || sourceBytes > SOURCE_BYTES)
fail('Transcript source capacity exceeded');
@@ -550,6 +581,7 @@
const value = copyTiming(timing);
if (timings.has(value.turn)) fail('Duplicate transcript timing');
timings.set(value.turn, value);
+ retainCurrent(value, encodedSize(value));
if (timings.size > 4096) fail('Transcript timing capacity exceeded');
}
const owner = (caller, token) => {
@@ -596,7 +628,14 @@
}
const base = revision++;
counters.updates++;
- for (const mount of [...mounts.values()]) mount.enqueue(makeEvents(base, revision));
+ const readers = [...mounts.values()];
+ if (!readers.length) return;
+ // Immutable payloads are shared; each reader keeps its own bounded queue.
+ for (const event of makeEvents(base, revision)) {
+ Object.freeze(event);
+ const size = encodedSize(event);
+ for (const mount of readers) mount.enqueue(event, size);
+ }
};
const replaceEvents = function* (entry, append, base, revision) {
let offset = 0;
@@ -618,7 +657,10 @@
fail('Transcript source capacity exceeded');
}
sources.set(entry.key, entry);
+ retainCurrent(entry, entry.encoded.length);
+ if (previous) releaseCurrent(previous);
sourceBytes = size;
+ boundHistory();
return true;
};
const page = (input, caller) => {
@@ -639,10 +681,12 @@
bytes(input.locale) > 32
)
fail('Invalid transcript open');
- if (mounts.has(document) || mounts.size >= 4) fail('Transcript mount capacity exceeded');
+ if (mounts.has(document)) fail('Transcript mount is already open');
const fence = revision;
let snapshot = [...sources.values()];
let snapshotTimings = new Map(timings);
+ for (const entry of snapshot) acquireSnapshot(entry);
+ for (const value of snapshotTimings.values()) acquireSnapshot(value);
const cursors = new Map();
const cursorValues = new Map();
const prefix = `m${++mountSequence}`;
@@ -655,6 +699,8 @@
live = false;
mounts.delete(document);
counters.closed++;
+ for (const entry of snapshot) releaseSnapshot(entry);
+ for (const value of snapshotTimings.values()) releaseSnapshot(value);
snapshot = [];
snapshotTimings.clear();
cursors.clear();
@@ -690,16 +736,14 @@
queueBytes = 0;
release();
},
- enqueue(events) {
- for (const event of events) {
- const size = encodedSize(event);
- if (size > WIRE_BYTES || queue.length >= 8192 || queueBytes + size > SOURCE_BYTES) {
- mount.invalidate();
- return;
- }
- queue.push(event);
- queueBytes += size;
+ enqueue(event, size) {
+ if (!live) return;
+ if (size > WIRE_BYTES || queue.length >= 8192 || queueBytes + size > SOURCE_BYTES) {
+ mount.invalidate();
+ return;
}
+ queue.push(event);
+ queueBytes += size;
wake?.();
},
page(input) {
@@ -856,7 +900,9 @@
const previous = sources.get(identity);
if (!previous) return;
sources.delete(identity);
+ releaseCurrent(previous);
sourceBytes -= previous.encoded.length;
+ boundHistory();
publish((base, revision) => [{ kind: 'remove', base, revision, key: previous.block.key }]);
},
timing(input) {
@@ -866,17 +912,26 @@
invalidate();
fail('Transcript timing capacity exceeded');
}
- if (JSON.stringify(timings.get(value.turn)) === JSON.stringify(value)) return;
+ const previous = timings.get(value.turn);
+ if (JSON.stringify(previous) === JSON.stringify(value)) return;
timings.set(value.turn, value);
+ retainCurrent(value, encodedSize(value));
+ if (previous) releaseCurrent(previous);
+ boundHistory();
publish((base, revision) => [{ kind: 'timing', base, revision, timing: value }]);
},
close() {
closing ??= (async () => {
closed = true;
for (const mount of [...mounts.values()]) mount.cancel();
+ for (const entry of sources.values()) releaseCurrent(entry);
+ for (const value of timings.values()) releaseCurrent(value);
sources.clear();
+ sourceBytes = 0;
timings.clear();
await Promise.all([reader.close(), streamer.close()]);
+ if (retained.size || historicalBytes !== 0)
+ fail('Transcript retention was not fully released');
})();
return closing;
},
@@ -970,7 +1025,6 @@
stream: (name, open, options) =>
register('remote_stream', { ...options, name }, (input, call) =>
remoteResult(async () => {
- if (streams.size >= 32) throw new Error('Client stream capacity exceeded');
const handle = 'stream-' + ++streamSequence;
let stopped = false;
let stop;
diff --git a/crates/js-runtime/src/plugin/worker.rs b/crates/js-runtime/src/plugin/worker.rs
index 1a9cadebc4..2894de2c83 100644
--- a/crates/js-runtime/src/plugin/worker.rs
+++ b/crates/js-runtime/src/plugin/worker.rs
@@ -16,22 +16,26 @@
* specific language governing permissions and limitations
* under the License.
*/
-use super::{Command, Health, Limits, Result, State, Statistics, engine, failed};
+use super::{Command, Health, Limits, PollClock, Result, State, Statistics, engine, failed};
use deno_core::v8;
use futures_util::{StreamExt, future::LocalBoxFuture, stream::FuturesUnordered};
-use std::{collections::BTreeMap, future::poll_fn, sync::Arc, task::Poll};
+use std::{
+ collections::BTreeMap,
+ future::poll_fn,
+ sync::{Arc, atomic::Ordering},
+ task::Poll,
+};
use tokio::sync::{OwnedSemaphorePermit, mpsc, oneshot, watch};
struct Loaded {
code: engine::Module,
calls: usize,
closing: bool,
- _slot: OwnedSemaphorePermit,
}
struct Request {
module: u64,
reply: oneshot::Sender<Result<serde_json::Value>>,
- _slot: OwnedSemaphorePermit,
+ _slot: Option<OwnedSemaphorePermit>,
_bytes: OwnedSemaphorePermit,
}
type Pending = FuturesUnordered<LocalBoxFuture<'static, (u64, Result<v8::Global<v8::Value>>)>>;
@@ -43,9 +47,12 @@ pub(super) async fn run(
) -> Result<()> {
let mut states: BTreeMap<u64, watch::Sender<State>> = BTreeMap::new();
let mut requests = BTreeMap::<u64, Request>::new();
- let result = {
+ let result = async {
+ // Trusted runtime setup precedes the user-script clock. Keep its errors
+ // in this result so queued loads still receive the common cleanup below.
+ let mut runtime = engine::runtime(&health, &limits)?;
+ health.initializing.store(false, Ordering::SeqCst);
let serving = async {
- let mut runtime = engine::runtime(&health, &limits)?;
let mut modules = BTreeMap::<u64, Loaded>::new();
let mut pending = Pending::new();
let mut next_call = 0_u64;
@@ -74,7 +81,6 @@ pub(super) async fn run(
name,
source,
state,
- slot,
bytes,
} => {
match engine::load(&mut runtime, &name, &source, bootstrap, id) {
@@ -92,7 +98,6 @@ pub(super) async fn run(
code,
calls: 0,
closing: false,
- _slot: slot,
},
);
state.send_replace(State::Ready);
@@ -196,15 +201,17 @@ pub(super) async fn run(
};
let mut serving = std::pin::pin!(serving);
poll_fn(|cx| {
- health
- .polling
- .send_replace(Some(tokio::time::Instant::now()));
+ health.polling.send_replace(Some(PollClock {
+ started: tokio::time::Instant::now(),
+ initializing: health.initializing.load(Ordering::SeqCst),
+ }));
let result = serving.as_mut().poll(cx);
health.polling.send_replace(None);
result
})
.await
- };
+ }
+ .await;
// Runtime, module globals and pending promises have left scope before cleanup
// acknowledgements. Host resource leases are managed by the Fiber above us.
if let Err(error) = &result {
diff --git a/crates/js-runtime/tests/integration/plugin_vm.rs b/crates/js-runtime/tests/integration/plugin_vm.rs
index 50d15086cb..445531909a 100644
--- a/crates/js-runtime/tests/integration/plugin_vm.rs
+++ b/crates/js-runtime/tests/integration/plugin_vm.rs
@@ -21,6 +21,8 @@ use maka_js_runtime::plugin::{Bridge, Error, Limits, Module, Pool, Vm};
use serde_json::{Value, json};
use std::time::Duration;
+mod inventory;
+
struct Relay(Module);
impl Bridge for Relay {
fn call(
@@ -36,7 +38,7 @@ impl Bridge for Relay {
#[tokio::test]
async fn cross_vm_host_calls_preserve_values_and_retirement_does_not_retarget_or_deadlock() {
tokio::time::timeout(Duration::from_secs(10), async {
- let pool = Pool::new(Limits::default(), 1).unwrap();
+ let pool = Pool::new(Limits::default());
let shared = pool.shared().unwrap();
let dedicated = pool.dedicated("service-generation").unwrap();
let service = dedicated.load("service.mjs".into(), r#"
@@ -232,11 +234,11 @@ async fn runaway_terminates_its_vm_and_not_an_independent_vm() {
synchronous_slice: Duration::from_millis(200),
..Limits::default()
};
- let pool = Pool::new(limits, 1).unwrap();
+ let pool = Pool::new(limits);
let shared = pool.shared().unwrap();
let dedicated = pool.dedicated("separate-generation").unwrap();
let same_generation = pool.dedicated("separate-generation").unwrap();
- assert!(pool.dedicated("another-generation").is_err());
+ let other = pool.dedicated("another-generation").unwrap();
let innocent = shared
.load(
"innocent.mjs".into(),
@@ -272,10 +274,12 @@ async fn runaway_terminates_its_vm_and_not_an_independent_vm() {
innocent.close().await.unwrap();
runaway.close().await.unwrap();
assert_eq!(call(&separate, "ping").await, json!(2));
+ assert!(!other.is_terminated());
separate.close().await.unwrap();
shared.shutdown().await;
dedicated.shutdown().await;
- // Retaining dead handles must neither consume capacity nor revive a VM.
+ other.shutdown().await;
+ // Retaining dead handles must not revive or retarget a VM.
let replacement = pool.dedicated("another-generation").unwrap();
assert!(!replacement.is_terminated());
replacement.shutdown().await;
diff --git a/crates/js-runtime/tests/integration/plugin_vm/inventory.rs b/crates/js-runtime/tests/integration/plugin_vm/inventory.rs
new file mode 100644
index 0000000000..2f65f41a90
--- /dev/null
+++ b/crates/js-runtime/tests/integration/plugin_vm/inventory.rs
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+
+#[tokio::test]
+async fn shared_vm_keeps_eighty_modules_then_reclaims_and_reloads_them() {
+ tokio::time::timeout(Duration::from_secs(15), async {
+ let pool = Pool::new(Limits::default());
+ let vm = pool.shared().unwrap();
+ let mut previous_keys = std::collections::BTreeSet::new();
+ for generation in 0..2 {
+ let modules = (0..80).map(|index| {
+ vm.load(format!("entry-{index}.mjs"), format!(
+ "const identity = [{generation}, {index}]; export function value() {{ return identity; }}"
+ )).unwrap()
+ }).collect::<Vec<_>>();
+ for (index, module) in modules.iter().enumerate() {
+ assert_eq!(call(module, "value").await, json!([generation, index]));
+ assert!(previous_keys.insert(module.host_key()), "module identities are never recycled");
+ }
+ let snapshot = pool.shared().unwrap().statistics(false).await.unwrap();
+ assert_eq!(snapshot.modules, 80);
+ assert_eq!(snapshot.pending_calls, 0);
+ for module in modules {
+ let weak = module.downgrade();
+ module.close().await.unwrap();
+ assert!(module.call(vec!["value".into()], vec![]).await.is_err());
+ drop(module);
+ assert!(weak.upgrade().is_none());
+ }
+ assert_eq!(vm.statistics(true).await.unwrap().modules, 0);
+ }
+ vm.shutdown().await;
+ }).await.expect("eighty small modules drain and reload without sleeps");
+}
+
+struct NoHostCalls;
+impl Bridge for NoHostCalls {
+ fn call(
+ &self,
+ method: String,
+ _: Value,
+ ) -> futures_util::future::BoxFuture<'static, Result<Value, Error>> {
+ panic!("business lifetime fixture unexpectedly called Host method {method}")
+ }
+}
+
+#[tokio::test]
+async fn shared_sdk_business_tasks_do_not_reserve_ordinary_call_slots() {
+ use maka_js_runtime::plugin::Lifecycle;
+ use std::sync::Arc;
+ const SOURCE: &str = r#"
+let activations = 0, started = 0;
+export default async function activate(ctx) {
+ activations++;
+ ctx.run(async () => { started++; await ctx.signal.wait(); });
+ await ctx.remote.method('stats', () => ({ activations, started }));
+}
+"#;
+ tokio::time::timeout(Duration::from_secs(30), async {
+ let limits = Limits::default();
+ assert_eq!(limits.heap_bytes, 128 * 1024 * 1024);
+ let vm = Vm::new(limits).unwrap();
+ let plain = vm
+ .load(
+ "not-sdk.mjs".into(),
+ "export function effective() { throw new Error('must not run'); }".into(),
+ )
+ .unwrap();
+ assert!(
+ plain
+ .start_tasks()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("SDK plugin")
+ );
+ plain.close().await.unwrap();
+ let mut modules = Vec::new();
+ for index in 0..130 {
+ let module = vm
+ .load_plugin(
+ format!("business-{index}.mjs"),
+ SOURCE.into(),
+ Arc::new(NoHostCalls),
+ )
+ .unwrap();
+ assert!(
+ module
+ .start_tasks()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("Invalid effective transition")
+ );
+ let registrations = module
+ .call(vec!["activate".into()], vec![json!({}), Value::Null])
+ .await
+ .unwrap();
+ let stats = registrations[0]["callback"].clone();
+ let running = module.clone();
+ let tasks = tokio::spawn(async move { running.start_tasks().await });
+ loop {
+ let value = module
+ .call(
+ vec!["invoke".into()],
+ vec![stats.clone(), Value::Null, json!({})],
+ )
+ .await
+ .unwrap();
+ assert_eq!(value["value"]["activations"], 1);
+ if value["value"]["started"] == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ modules.push((module, stats, tasks));
+ }
+ let current = vm.statistics(false).await.unwrap();
+ assert_eq!(current.modules, 130);
+ assert_eq!(current.pending_calls, 130);
+ for (module, stats, tasks) in &modules {
+ assert!(
+ !tasks.is_finished(),
+ "each business lifetime remains pending"
+ );
+ let value = module
+ .call(
+ vec!["invoke".into()],
+ vec![stats.clone(), Value::Null, json!({})],
+ )
+ .await
+ .unwrap();
+ assert_eq!(value["value"], json!({"activations":1,"started":1}));
+ }
+ assert!(
+ modules[0]
+ .0
+ .start_tasks()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("Invalid effective transition")
+ );
+ assert!(
+ !modules[0].2.is_finished(),
+ "duplicate start cannot replace the original lifetime"
+ );
+ for (module, _, tasks) in modules {
+ module.lifecycle(Lifecycle::Retire).await.unwrap();
+ tasks.await.unwrap().unwrap();
+ module.lifecycle(Lifecycle::Dispose).await.unwrap();
+ module.close().await.unwrap();
+ }
+ let settled = vm.statistics(true).await.unwrap();
+ assert_eq!(settled.modules, 0);
+ assert_eq!(settled.pending_calls, 0);
+ assert!(!vm.is_terminated());
+ vm.shutdown().await;
+ })
+ .await
+ .expect("SDK business jobs share the unchanged 128 MiB VM and retire through reserved control");
+}
diff --git a/crates/plugins/src/terminal_ui/view.rs b/crates/plugins/src/terminal_ui/view.rs
index c78af015cf..bae99ecdd4 100644
--- a/crates/plugins/src/terminal_ui/view.rs
+++ b/crates/plugins/src/terminal_ui/view.rs
@@ -505,7 +505,6 @@ pub(crate) fn route(value: &Value) -> Result<(), Error> {
#[derive(Default)]
struct Walk<'a> {
nodes: usize,
- transcripts: usize,
inputs: BTreeSet<&'a str>,
actions: BTreeSet<&'a str>,
}
@@ -735,10 +734,6 @@ impl View {
route(context)?;
}
Node::Transcript { resource, .. } => {
- walk.transcripts += 1;
- if walk.transcripts > 4 {
- return Err(invalid());
- }
resource.validate()?;
}
}
diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs
index fad50f08a0..57d108ded0 100644
--- a/crates/protocol/src/lib.rs
+++ b/crates/protocol/src/lib.rs
@@ -60,7 +60,7 @@ use serde::Serialize;
use serde_json::Value;
pub const PROTOCOL_VERSION: u64 = 0;
-pub const COMPATIBILITY_EPOCH: u64 = 194;
+pub const COMPATIBILITY_EPOCH: u64 = 195;
pub const COMPOSITION_ID: &str = "maka.interactive";
pub const MAX_MESSAGE_BYTES: usize = 768 * 1024;
pub const MAX_IN_FLIGHT_DOMAIN_REQUESTS: usize = 64;
diff --git a/crates/runtime-host/src/plugins/javascript.rs b/crates/runtime-host/src/plugins/javascript.rs
index 7076b942b8..50cbc93069 100644
--- a/crates/runtime-host/src/plugins/javascript.rs
+++ b/crates/runtime-host/src/plugins/javascript.rs
@@ -47,17 +47,17 @@ use std::time::Duration;
pub(crate) struct Loader {
pool: Arc<Pool>,
- presenters: Arc<presenter::Capacity>,
+ presenter_limits: Limits,
executions: Weak<Executions>,
}
impl Loader {
pub fn new(executions: &Arc<Executions>) -> Result<Self, maka_plugins::Error> {
Ok(Self {
- pool: Arc::new(Pool::new(Limits::default(), 4).map_err(invalid)?),
- presenters: Arc::new(presenter::Capacity::new(Limits {
+ pool: Arc::new(Pool::new(Limits::default())),
+ presenter_limits: Limits {
synchronous_slice: Duration::from_millis(200),
..Limits::default()
- })),
+ },
executions: Arc::downgrade(executions),
})
}
@@ -82,7 +82,7 @@ impl PackageLoader for Loader {
generation: format!("{}:{}", package.manifest().id, package.digest()),
remote: Arc::new(remote::Source {
package: package.clone(),
- presenters: self.presenters.clone(),
+ presenter_limits: self.presenter_limits.clone(),
catalog: self
.executions
.upgrade()
@@ -176,7 +176,7 @@ impl Plugin for JavaScript {
context
.lifecycle
.spawn("JavaScript business tasks", async move {
- if let Err(error) = business.call(vec!["effective".into()], vec![]).await {
+ if let Err(error) = business.start_tasks().await {
owner.retire();
return Err(error.to_string());
}
diff --git a/crates/runtime-host/src/plugins/javascript/invocation.rs b/crates/runtime-host/src/plugins/javascript/invocation.rs
index cffc3868de..efc9d25221 100644
--- a/crates/runtime-host/src/plugins/javascript/invocation.rs
+++ b/crates/runtime-host/src/plugins/javascript/invocation.rs
@@ -81,11 +81,6 @@ impl Calls {
view: maka_plugins::filesystem::ReadDirectory,
) -> Result<ReadGuard, maka_plugins::Error> {
let mut reads = self.reads.lock().unwrap();
- if reads.len() >= 128 {
- return Err(maka_plugins::Error::Invalid(
- "read-view capacity exceeded".into(),
- ));
- }
let id = uuid::Uuid::new_v4().to_string();
reads.insert(id.clone(), ReadEntry { view, remote: None });
Ok(ReadGuard {
@@ -117,11 +112,6 @@ impl Calls {
return Err(maka_plugins::Error::Retired);
}
let mut reads = self.reads.lock().unwrap();
- if reads.len() >= 128 {
- return Err(maka_plugins::Error::Invalid(
- "read-view capacity exceeded".into(),
- ));
- }
let id = uuid::Uuid::new_v4().to_string();
reads.insert(
id.clone(),
@@ -141,11 +131,8 @@ impl Calls {
return Err(maka_plugins::remote::Error::Cancelled);
}
let mut calls = self.remotes.lock().unwrap();
- if calls.len() >= 128 {
- return Err(maka_plugins::remote::Error::Invalid(
- "Remote call capacity exceeded".into(),
- ));
- }
+ // Stream callers retain authority until close. These owned identities
+ // are not executing work; the VM separately bounds ordinary calls.
let id = uuid::Uuid::new_v4().to_string();
caller.cancellation = caller.cancellation.child_token();
let cancellation = caller.cancellation.clone();
@@ -207,3 +194,6 @@ impl Drop for Guard {
self.calls.invocations.lock().unwrap().remove(&self.id);
}
}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/runtime-host/src/plugins/javascript/invocation/tests.rs b/crates/runtime-host/src/plugins/javascript/invocation/tests.rs
new file mode 100644
index 0000000000..ed0839d6bf
--- /dev/null
+++ b/crates/runtime-host/src/plugins/javascript/invocation/tests.rs
@@ -0,0 +1,192 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use futures_util::future::BoxFuture;
+use maka_plugins::{
+ composition::Scope,
+ fiber::Fiber,
+ filesystem::{ReadRoot, entries::ReadFile},
+ remote::{self, Caller, Error},
+};
+
+struct UnusedViews;
+impl remote::Views for UnusedViews {
+ fn authorize(
+ &self,
+ _: maka_plugins::authorization::Request,
+ ) -> BoxFuture<'_, Result<maka_plugins::call::Owned, Error>> {
+ unreachable!()
+ }
+ fn session(&self) -> BoxFuture<'_, Result<remote::SessionView, Error>> {
+ unreachable!()
+ }
+ fn workspace(
+ &self,
+ _: remote::WorkspaceViewInput,
+ ) -> BoxFuture<'_, Result<remote::SessionView, Error>> {
+ unreachable!()
+ }
+ fn query_database(
+ &self,
+ _: maka_plugins::filesystem::database::Read,
+ ) -> BoxFuture<
+ '_,
+ Result<
+ Vec<maka_plugins::filesystem::database::Table>,
+ maka_plugins::filesystem::database::Error,
+ >,
+ > {
+ unreachable!()
+ }
+}
+fn caller() -> Caller {
+ Caller {
+ connection_id: uuid::Uuid::new_v4(),
+ client_instance_id: "read-handle-test".into(),
+ document_id: uuid::Uuid::new_v4(),
+ session_id: None,
+ access: remote::Access::Granted,
+ views: Arc::new(UnusedViews),
+ resources: Arc::default(),
+ cancellation: CancellationToken::new(),
+ }
+}
+
+#[tokio::test]
+async fn read_handles_follow_their_borrower_or_remote_owner_without_inventory_limit() {
+ let directory = tempfile::tempdir().unwrap();
+ std::fs::write(directory.path().join("allowed"), b"contents").unwrap();
+ std::fs::write(directory.path().join("private"), b"secret").unwrap();
+ let owner = Fiber::new("example.views", "read-test", Scope::Profile).unwrap();
+ owner.begin_loading().unwrap();
+ owner.ready().unwrap();
+ owner.publish().unwrap();
+ let root = ReadRoot::open(directory.path())
+ .await
+ .unwrap()
+ .select(["allowed".into()].into())
+ .unwrap();
+ let calls = Arc::new(Calls::new(Default::default()));
+ let first = calls.enter_remote(caller()).unwrap();
+ let second = calls.enter_remote(caller()).unwrap();
+ let first_view = root.bind(owner.context(), first.cancellation.clone());
+ let second_view = root.bind(owner.context(), second.cancellation.clone());
+ let first_handles = (0..130)
+ .map(|_| calls.remote_read(&first.id, first_view.clone()).unwrap())
+ .collect::<Vec<_>>();
+ let second_handle = calls.remote_read(&second.id, second_view.clone()).unwrap();
+ let borrowed = (0..130)
+ .map(|_| {
+ calls
+ .borrow_read(root.bind(owner.context(), CancellationToken::new()))
+ .unwrap()
+ })
+ .collect::<Vec<_>>();
+ let all = first_handles
+ .iter()
+ .cloned()
+ .chain([second_handle.clone()])
+ .chain(borrowed.iter().map(|guard| guard.id.clone()))
+ .collect::<std::collections::BTreeSet<_>>();
+ assert_eq!(
+ all.len(),
+ 261,
+ "every retained capability has its own identity"
+ );
+ for id in &all {
+ assert!(calls.read(id).is_ok());
+ }
+ let read = |path: &str, limit| ReadFile {
+ path: path.into(),
+ offset: 0,
+ limit,
+ };
+ assert!(
+ calls
+ .read(&first_handles[0])
+ .unwrap()
+ .read(read("allowed", 1))
+ .await
+ .is_ok()
+ );
+ assert!(
+ calls
+ .read(&first_handles[0])
+ .unwrap()
+ .read(read("private", 1))
+ .await
+ .is_err()
+ );
+ assert!(
+ calls
+ .read(&first_handles[0])
+ .unwrap()
+ .read(read("allowed", 1024 * 1024 + 1))
+ .await
+ .is_err()
+ );
+ first.cancellation.cancel();
+ assert!(calls.remote_read(&first.id, first_view.clone()).is_err());
+ assert!(
+ calls
+ .remote_read("foreign-authority", second_view.clone())
+ .is_err()
+ );
+ assert!(calls.remote(&first.id).is_err());
+ assert!(
+ calls
+ .read(&first_handles[0])
+ .unwrap()
+ .read(read("allowed", 1))
+ .await
+ .is_err()
+ );
+ let first_authority = first.id.clone();
+ drop(first);
+ for id in &first_handles {
+ assert!(calls.read(id).is_err());
+ }
+ assert!(calls.remote_read(&first_authority, first_view).is_err());
+ assert!(calls.remote(&second.id).is_ok());
+ assert!(
+ calls
+ .read(&second_handle)
+ .unwrap()
+ .read(read("allowed", 1))
+ .await
+ .is_ok()
+ );
+ for guard in &borrowed {
+ assert!(calls.read(&guard.id).is_ok());
+ }
+ let borrowed_ids = borrowed
+ .iter()
+ .map(|guard| guard.id.clone())
+ .collect::<Vec<_>>();
+ drop(borrowed);
+ for id in &borrowed_ids {
+ assert!(calls.read(id).is_err());
+ }
+ assert!(calls.read(&second_handle).is_ok());
+ drop(second);
+ assert!(calls.read(&second_handle).is_err());
+ assert!(calls.reads.lock().unwrap().is_empty());
+ assert!(calls.remotes.lock().unwrap().is_empty());
+}
diff --git a/crates/runtime-host/src/plugins/javascript/presenter.rs b/crates/runtime-host/src/plugins/javascript/presenter.rs
index b4afd7409f..ec2c9a20a6 100644
--- a/crates/runtime-host/src/plugins/javascript/presenter.rs
+++ b/crates/runtime-host/src/plugins/javascript/presenter.rs
@@ -28,27 +28,13 @@ use maka_plugins::{
};
use serde_json::Value;
use std::{sync::Arc, time::Duration};
-use tokio::sync::{Semaphore, watch};
+use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
-/// One Host-wide admission budget, independent of business Dedicated VMs.
-/// Four bounds simultaneous page heaps; hidden drafts do not reserve a slot.
-pub(super) struct Capacity {
- slots: Arc<Semaphore>,
- limits: Limits,
-}
-impl Capacity {
- pub fn new(limits: Limits) -> Self {
- Self {
- slots: Arc::new(Semaphore::new(4)),
- limits,
- }
- }
-}
pub(super) struct Factory {
source: String,
name: String,
- capacity: Arc<Capacity>,
+ limits: Limits,
observations: Vec<api::Observation>,
backend: Arc<dyn Method>,
retiring: CancellationToken,
@@ -57,7 +43,7 @@ impl Factory {
pub fn new(
package: &Package,
entry: &str,
- capacity: Arc<Capacity>,
+ limits: Limits,
backend: Arc<dyn Method>,
retiring: CancellationToken,
observations: Vec<api::Observation>,
@@ -70,7 +56,7 @@ impl Factory {
Ok(Self {
source,
name: format!("{}:{entry}", package.digest()),
- capacity,
+ limits,
observations,
backend,
retiring,
@@ -85,13 +71,7 @@ impl api::Factory for Factory {
if cancellation.is_cancelled() || self.retiring.is_cancelled() {
return Err(Error::Retired);
}
- let reservation = self
- .capacity
- .slots
- .clone()
- .try_acquire_owned()
- .map_err(|_| Error::Provider("terminal page VM capacity exhausted".into()))?;
- let vm = Vm::new(self.capacity.limits.clone()).map_err(provider)?;
+ let vm = Vm::new(self.limits.clone()).map_err(provider)?;
let bridge = Arc::new(bridge::PageBridge::new(self.backend.clone()));
let module = match vm.load_presenter(self.name.clone(), self.source.clone(), bridge.clone())
{
@@ -99,7 +79,6 @@ impl api::Factory for Factory {
Err(error) => {
tokio::spawn(async move {
vm.shutdown().await;
- drop(reservation);
});
return Err(provider(error));
}
@@ -120,6 +99,13 @@ impl api::Factory for Factory {
_ = retiring.cancelled() => {},
_ = vm.failed() => {},
}
+ // Read the original health cause before our own shutdown records a
+ // normal stop. This is diagnostic data, not Host cleanup authority.
+ let vm_fault = cancelling.vm_failure();
+ #[cfg(test)]
+ if let Some(fault) = &vm_fault {
+ eprintln!("terminal page VM failure: {fault}");
+ }
stop.cancel();
let ids = bridge.cancel();
// Cooperative signals are best effort; worker teardown remains the
@@ -130,22 +116,26 @@ impl api::Factory for Factory {
}
})
.await;
- // A permit remains held until actual worker teardown, even if a
- // caller stops waiting. VM death is not unknown Host cleanup.
+ // Worker teardown remains owned even if a caller stops waiting.
+ // VM death is not unknown Host cleanup.
vm.shutdown().await;
- let result = bridge.drained().await;
- drop(reservation);
- done.send_replace(Some(result));
+ let cleanup = bridge.drained().await;
+ done.send_replace(Some(Closed { cleanup, vm_fault }));
});
Ok(page)
}
}
struct Page(Arc<Inner>);
+#[derive(Clone)]
+struct Closed {
+ cleanup: Result<(), Error>,
+ vm_fault: Option<maka_js_runtime::plugin::Error>,
+}
struct Inner {
module: Module,
bridge: Arc<bridge::PageBridge>,
stop: CancellationToken,
- closed: watch::Receiver<Option<Result<(), Error>>>,
+ closed: watch::Receiver<Option<Closed>>,
}
impl Drop for Inner {
fn drop(&mut self) {
@@ -153,12 +143,12 @@ impl Drop for Inner {
}
}
impl Inner {
- async fn closed(&self) -> Result<(), Error> {
+ async fn closed(&self) -> Result<Closed, Error> {
let mut closed = self.closed.clone();
let wait = async {
loop {
if let Some(result) = closed.borrow_and_update().clone() {
- return result;
+ return Ok(result);
}
closed
.changed()
@@ -176,7 +166,12 @@ impl api::Page for Page {
let page = self.0.clone();
Box::pin(async move {
if page.stop.is_cancelled() {
- return Err(Error::Retired);
+ let fault = page
+ .closed
+ .borrow()
+ .as_ref()
+ .and_then(|closed| closed.vm_fault.clone());
+ return Err(fault.map(provider).unwrap_or(Error::Retired));
}
let cancellation = caller.cancellation.clone();
let guard = page.bridge.enter(&input, caller)?;
@@ -201,7 +196,11 @@ impl api::Page for Page {
if let Some(outcome) = guard.outcome() {
return Ok(outcome);
}
- closed?;
+ let closed = closed?;
+ closed.cleanup?;
+ if let Some(fault) = closed.vm_fault {
+ return Err(provider(fault));
+ }
}
result
})
@@ -215,7 +214,7 @@ impl api::Page for Page {
}
fn close(&self) -> BoxFuture<'_, Result<(), Error>> {
self.cancel();
- Box::pin(self.0.closed())
+ Box::pin(async move { self.0.closed().await?.cleanup })
}
}
/// Only the document dispatcher can invoke this registration's private backend.
diff --git a/crates/runtime-host/src/plugins/javascript/presenter/tests.rs b/crates/runtime-host/src/plugins/javascript/presenter/tests.rs
index a53be0378a..689cc8203f 100644
--- a/crates/runtime-host/src/plugins/javascript/presenter/tests.rs
+++ b/crates/runtime-host/src/plugins/javascript/presenter/tests.rs
@@ -155,7 +155,7 @@ async fn page_vm_failure_preserves_sibling_factory_and_business_job() {
let business = business_vm.load_plugin("business.mjs".into(), BUSINESS.into(), clock.clone()).unwrap();
business.call(vec!["activate".into()], vec![json!({}), Value::Null]).await.unwrap();
let running = business.clone();
- let job = tokio::spawn(async move { running.call(vec!["effective".into()], vec![]).await });
+ let job = tokio::spawn(async move { running.start_tasks().await });
clock.entered.acquire().await.unwrap().forget();
let entered = Arc::new(Semaphore::new(0));
let backend = Arc::new(Backend(std::sync::Mutex::default(), entered.clone()));
@@ -164,16 +164,19 @@ async fn page_vm_failure_preserves_sibling_factory_and_business_job() {
("host.mjs".into(), BUSINESS.as_bytes().to_vec()),
("page.mjs".into(), SOURCE.as_bytes().to_vec()),
])).unwrap();
- let capacity = Arc::new(Capacity::new(limits));
- let factory = Factory::new(&package, "page.mjs", capacity.clone(), backend.clone(), CancellationToken::new(), vec![]).unwrap();
- assert!(Factory::new(&package, "../page.mjs", capacity.clone(), backend.clone(), CancellationToken::new(), vec![]).is_err());
+ let factory = Factory::new(&package, "page.mjs", limits.clone(), backend.clone(), CancellationToken::new(), vec![]).unwrap();
+ assert!(Factory::new(&package, "../page.mjs", limits, backend.clone(), CancellationToken::new(), vec![]).is_err());
let page_a = factory.open(CancellationToken::new()).unwrap();
let page_b = factory.open(CancellationToken::new()).unwrap();
- let third = factory.open(CancellationToken::new()).unwrap();
- let fourth = factory.open(CancellationToken::new()).unwrap();
- assert!(factory.open(CancellationToken::new()).is_err());
- third.close().await.unwrap();
- fourth.close().await.unwrap();
+ // Keep 33 isolated page VMs alive together. Instance count is not an
+ // admission boundary, and each runs its own JavaScript factory.
+ let pages: Vec<_> = (0..31).map(|_| factory.open(CancellationToken::new()).unwrap()).collect();
+ for (index, page) in pages.iter().enumerate() {
+ let value = page.call(read(Value::Null), caller(uuid::Uuid::new_v4())).await
+ .unwrap_or_else(|error| panic!("page {} first Read failed: {error}", index + 3));
+ assert_eq!(value["view"]["revision"], "1");
+ assert_eq!(value["view"]["root"]["spans"][0]["text"], "1");
+ }
let a = caller(uuid::Uuid::new_v4());
let b = caller(uuid::Uuid::new_v4());
assert_eq!(page_b.call(read(Value::Null), b.clone()).await.unwrap()["view"]["revision"], "1");
@@ -185,10 +188,16 @@ async fn page_vm_failure_preserves_sibling_factory_and_business_job() {
assert_eq!(sibling["view"]["revision"], "1");
assert_eq!(sibling["view"]["root"]["spans"][0]["text"], "2");
assert!(!fault.is_finished(), "sibling must complete before A's watchdog failure");
- assert!(matches!(fault.await.unwrap(), Err(Error::Provider(_) | Error::Retired | Error::Cancelled)));
+ assert!(matches!(fault.await.unwrap(), Err(Error::Provider(message))
+ if message.contains("synchronous execution budget exceeded")),
+ "the original VM fault must survive incidental Caller cancellation");
page_a.close().await.unwrap();
step(&clock).await;
assert_eq!(stats(&business).await, json!({"activations":1,"ticks":2}));
+ for page in pages { page.close().await.unwrap(); }
+ step(&clock).await;
+ assert_eq!(stats(&business).await, json!({"activations":1,"ticks":3}));
+ // B stays usable after its many siblings have completed VM teardown.
let submission = json!({"kind":"submit","route":null,"revision":"r1","action":"save","fields":{},"locale":"en"});
assert_eq!(page_b.call(submission.clone(), b.clone()).await.unwrap()["kind"], "applied");
assert!(backend.0.lock().unwrap().contains(&(submission, b.document_id)));
@@ -196,8 +205,60 @@ async fn page_vm_failure_preserves_sibling_factory_and_business_job() {
assert!(page_b.call(read(json!("write")), b).await.is_err());
assert_eq!(backend.0.lock().unwrap().len(), calls + 1);
page_b.close().await.unwrap();
- assert_eq!(capacity.slots.available_permits(), 4);
+ let reopened = factory.open(CancellationToken::new()).unwrap();
+ let fresh = reopened.call(read(Value::Null), caller(uuid::Uuid::new_v4())).await.unwrap();
+ assert_eq!(fresh["view"]["revision"], "1");
+ assert_eq!(fresh["view"]["root"]["spans"][0]["text"], "1");
+ reopened.close().await.unwrap();
business_vm.shutdown().await;
assert!(job.await.unwrap().is_err());
}).await.unwrap();
}
+
+#[tokio::test]
+async fn page_top_level_and_factory_loops_remain_watchdog_protected() {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ for (name, source) in [
+ (
+ "top-level-loop.mjs",
+ "while (true) {} export default function create() {}",
+ ),
+ (
+ "factory-loop.mjs",
+ "export default function create() { while (true) {} }",
+ ),
+ ] {
+ let backend = Arc::new(Backend(
+ std::sync::Mutex::default(),
+ Arc::new(Semaphore::new(0)),
+ ));
+ let factory = Factory {
+ source: source.into(),
+ name: name.into(),
+ limits: Limits {
+ synchronous_slice: Duration::from_millis(200),
+ ..Limits::default()
+ },
+ observations: vec![],
+ backend: backend.clone(),
+ retiring: CancellationToken::new(),
+ };
+ let page = factory.open(CancellationToken::new()).unwrap();
+ let error = page
+ .call(read(Value::Null), caller(uuid::Uuid::new_v4()))
+ .await
+ .unwrap_err();
+ page.close().await.unwrap();
+ assert!(
+ matches!(&error, Error::Provider(message)
+ if message.contains("synchronous execution budget exceeded")
+ && message.contains("poll began in script poll")
+ && message.contains("phase: script poll")),
+ "{name} must fail inside the user-script watchdog: {error}"
+ );
+ assert!(backend.0.lock().unwrap().is_empty());
+ }
+ })
+ .await
+ .expect("user loops and their VM teardown must make bounded progress");
+}
diff --git a/crates/runtime-host/src/plugins/javascript/registration/terminal.rs b/crates/runtime-host/src/plugins/javascript/registration/terminal.rs
index 58c8c4d2c1..270d7eee72 100644
--- a/crates/runtime-host/src/plugins/javascript/registration/terminal.rs
+++ b/crates/runtime-host/src/plugins/javascript/registration/terminal.rs
@@ -219,7 +219,7 @@ pub(super) fn stage(
presenter::Factory::new(
&source.package,
&entry,
- source.presenters.clone(),
+ source.presenter_limits.clone(),
backend,
lifecycle.stopping().map_err(super::super::message)?,
members,
diff --git a/crates/runtime-host/src/plugins/javascript/remote.rs b/crates/runtime-host/src/plugins/javascript/remote.rs
index 9417a91ce8..8ac61fdeac 100644
--- a/crates/runtime-host/src/plugins/javascript/remote.rs
+++ b/crates/runtime-host/src/plugins/javascript/remote.rs
@@ -27,7 +27,7 @@ use std::sync::{Arc, Mutex};
pub(super) struct Source {
pub package: maka_plugins::package::Package,
- pub presenters: Arc<super::presenter::Capacity>,
+ pub presenter_limits: maka_js_runtime::plugin::Limits,
pub catalog: maka_plugins::contributions::Catalog,
}
pub(super) struct Remote(pub Arc<Callback>);
@@ -76,7 +76,7 @@ impl Stream for JsStream {
let value = self
.callback
.module
- .call(vec!["streamNext".into()], vec![json!(self.handle)])
+ .stream_next(&self.handle)
.await
.map_err(|error| Error::Provider(error.to_string()))?;
let value = result(value)?;
@@ -119,7 +119,7 @@ impl Stream for JsStream {
.map_err(|_| Error::CleanupUnconfirmed)?;
self.callback
.module
- .call(vec!["streamClose".into()], vec![json!(self.handle)])
+ .stream_close(&self.handle)
.await
.map_err(|_| Error::CleanupUnconfirmed)?;
Ok(())
@@ -179,3 +179,6 @@ fn result(value: Value) -> Result<Value, Error> {
}),
}
}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/runtime-host/src/plugins/javascript/remote/tests.rs b/crates/runtime-host/src/plugins/javascript/remote/tests.rs
new file mode 100644
index 0000000000..3d254b5fc5
--- /dev/null
+++ b/crates/runtime-host/src/plugins/javascript/remote/tests.rs
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_js_runtime::plugin::{Limits, Vm};
+use std::time::Duration;
+use tokio::sync::Semaphore;
+
+mod fixture;
+mod retention;
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
+async fn idle_streams_preserve_business_capacity_and_close_under_saturated_work() {
+ tokio::time::timeout(Duration::from_secs(20), scenario())
+ .await
+ .unwrap();
+}
+
+async fn scenario() {
+ let vm = Vm::new(Limits::default()).unwrap();
+ let started = Arc::new(fixture::Started(Semaphore::new(0)));
+ let module = vm
+ .load_plugin(
+ "idle-streams.mjs".into(),
+ fixture::SOURCE.into(),
+ started.clone(),
+ )
+ .unwrap();
+ let registrations = module
+ .call(vec!["activate".into()], vec![json!({}), Value::Null])
+ .await
+ .unwrap();
+ let calls = Arc::new(super::super::invocation::Calls::new(Default::default()));
+ let provider = fixture::remote(&module, ®istrations, &calls, "idle");
+ let stats = fixture::remote(&module, ®istrations, &calls, "stats");
+ let mut streams = Vec::new();
+ let mut documents = Vec::new();
+ for _ in 0..130 {
+ let caller = fixture::caller();
+ documents.push(caller.document_id);
+ streams.push(provider.open(Value::Null, caller).await.unwrap());
+ }
+ let state = stats.call(Value::Null, fixture::caller()).await.unwrap();
+ assert_eq!(state["opened"], 130);
+ let authorities: Vec<String> = state["authorities"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|id| id.as_str().unwrap().to_owned())
+ .collect();
+ for (authority, document) in authorities.iter().zip(documents) {
+ assert_eq!(calls.remote(authority).unwrap().document_id, document);
+ }
+ let mut next = Box::pin(futures_util::future::join_all(
+ streams.iter().map(|stream| stream.next()),
+ ));
+ assert!(futures_util::poll!(next.as_mut()).is_pending());
+ loop {
+ let state = stats.call(Value::Null, fixture::caller()).await.unwrap();
+ if state["waiting"] == 130 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ // All 130 iterator promises are idle, while an ordinary business call works.
+ assert_eq!(
+ stats.call(Value::Null, fixture::caller()).await.unwrap()["activations"],
+ 1
+ );
+ assert!(
+ streams[0].next().await.is_err(),
+ "one pending Next per real SDK handle"
+ );
+ assert!(module.stream_next("missing-stream").await.is_err());
+
+ let blocker = vm
+ .load_with_bridge(
+ "ordinary-work.mjs".into(),
+ fixture::BLOCKER.into(),
+ Some(started.clone()),
+ )
+ .unwrap();
+ assert!(
+ blocker
+ .stream_next("stream-1")
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("SDK plugin")
+ );
+ assert!(
+ blocker
+ .stream_close("stream-1")
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("SDK plugin")
+ );
+ let mut work = Vec::new();
+ for _ in 0..128 {
+ let blocker = blocker.clone();
+ work.push(tokio::spawn(async move {
+ blocker
+ .call(vec!["wait".into()], vec![json!(blocker.host_key())])
+ .await
+ }));
+ // Each bridge acknowledgement proves a distinct ordinary call was
+ // dispatched and keeps its Promise pending until the reserved release.
+ started.0.acquire().await.unwrap().forget();
+ }
+ assert!(
+ stats
+ .call(Value::Null, fixture::caller())
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("VM call capacity exhausted")
+ );
+ for stream in &streams {
+ stream.cancel();
+ }
+ for result in next.await {
+ assert!(result.unwrap().is_none());
+ }
+ // Work is still saturated: both cancel and close must use reserved control.
+ for stream in streams {
+ stream.close().await.unwrap();
+ }
+ for authority in &authorities {
+ assert!(calls.remote(authority).is_err());
+ }
+ blocker.cancel_call("release".into()).await.unwrap();
+ for task in work {
+ assert_eq!(task.await.unwrap().unwrap(), "released");
+ }
+ let state = stats.call(Value::Null, fixture::caller()).await.unwrap();
+ assert_eq!(state["activations"], 1);
+ assert_eq!(state["waiting"], 0);
+ assert_eq!(state["closed"], 130);
+ drop(provider);
+ drop(stats);
+ module.close().await.unwrap();
+ blocker.close().await.unwrap();
+ assert_eq!(vm.statistics(false).await.unwrap().pending_calls, 0);
+ vm.shutdown().await;
+}
diff --git a/crates/runtime-host/src/plugins/javascript/remote/tests/fixture.rs b/crates/runtime-host/src/plugins/javascript/remote/tests/fixture.rs
new file mode 100644
index 0000000000..b84c6dde0d
--- /dev/null
+++ b/crates/runtime-host/src/plugins/javascript/remote/tests/fixture.rs
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_js_runtime::plugin::{Bridge, Error as VmError, Module};
+use maka_plugins::remote;
+use tokio::sync::Semaphore;
+use tokio_util::sync::CancellationToken;
+
+pub(super) const SOURCE: &str = r#"
+let activations = 0, opened = 0, waiting = 0, closed = 0;
+const authorities = [];
+export default async function activate(ctx) {
+ activations++;
+ await ctx.remote.stream('idle', (_, caller) => {
+ opened++;
+ authorities.push(caller.remoteAuthority);
+ let stopped = false, wake;
+ return {
+ async next() {
+ if (stopped) return { done: true };
+ waiting++;
+ await new Promise(resolve => { wake = resolve; });
+ waiting--;
+ return { done: true };
+ },
+ cancel() { stopped = true; wake?.(); },
+ close() { closed++; },
+ };
+ });
+ await ctx.remote.method('stats', () => ({ activations, opened, waiting, closed, authorities }));
+}
+"#;
+pub(super) const BLOCKER: &str = r#"
+const pending = [];
+export async function wait(key) {
+ const result = new Promise(resolve => pending.push(resolve));
+ await Deno.core.ops.op_maka_plugin(key, 'started', null);
+ return await result;
+}
+export function cancel() { for (const resolve of pending.splice(0)) resolve('released'); }
+export function streamNext() { throw new Error('arbitrary stream export must not run'); }
+export function streamClose() { throw new Error('arbitrary stream export must not run'); }
+"#;
+
+pub(super) struct Started(pub Semaphore);
+impl Bridge for Started {
+ fn call(&self, method: String, _: Value) -> BoxFuture<'static, Result<Value, VmError>> {
+ assert_eq!(method, "started");
+ self.0.add_permits(1);
+ Box::pin(async { Ok(Value::Null) })
+ }
+}
+struct Views;
+impl remote::Views for Views {
+ fn authorize(
+ &self,
+ _: maka_plugins::authorization::Request,
+ ) -> BoxFuture<'_, Result<maka_plugins::call::Owned, Error>> {
+ Box::pin(async { Err(Error::Retired) })
+ }
+ fn session(&self) -> BoxFuture<'_, Result<remote::SessionView, Error>> {
+ Box::pin(async { Err(Error::Retired) })
+ }
+ fn workspace(
+ &self,
+ _: remote::WorkspaceViewInput,
+ ) -> BoxFuture<'_, Result<remote::SessionView, Error>> {
+ Box::pin(async { Err(Error::Retired) })
+ }
+ fn query_database(
+ &self,
+ _: maka_plugins::filesystem::database::Read,
+ ) -> BoxFuture<
+ '_,
+ Result<
+ Vec<maka_plugins::filesystem::database::Table>,
+ maka_plugins::filesystem::database::Error,
+ >,
+ > {
+ panic!("fixture has no database authority")
+ }
+}
+pub(super) fn caller() -> Caller {
+ Caller {
+ connection_id: uuid::Uuid::new_v4(),
+ client_instance_id: "idle-stream-test".into(),
+ document_id: uuid::Uuid::new_v4(),
+ session_id: None,
+ access: remote::Access::Granted,
+ views: Arc::new(Views),
+ resources: Arc::default(),
+ cancellation: CancellationToken::new(),
+ }
+}
+
+pub(super) fn remote(
+ module: &Module,
+ registrations: &Value,
+ calls: &Arc<super::super::super::invocation::Calls>,
+ name: &str,
+) -> Remote {
+ Remote(Arc::new(Callback {
+ module: module.clone(),
+ id: registrations
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|entry| entry["name"] == name)
+ .unwrap()["callback"]
+ .as_u64()
+ .unwrap() as u32,
+ calls: calls.clone(),
+ }))
+}
+
+pub(super) const RETENTION: &str = r#"
+let activations = 0, store;
+const text = '界'.repeat(3 * 1024 * 1024);
+const block = revision => ({
+ key: { turn: 'turn', message: 'large', part: 'text' },
+ revision: String(revision), kind: 'assistant', content: { text },
+});
+export default async function activate(ctx) {
+ activations++;
+ store = await ctx.tui.transcriptResource('pressure', {
+ blocks: [block(1)], timings: [{ turn: 'turn', start_ms: 1 }],
+ });
+ await ctx.remote.method('control', async input => {
+ if (input.kind === 'replace') {
+ store.replace(block(input.revision));
+ store.timing({ turn: 'turn', start_ms: input.revision });
+ }
+ if (input.kind === 'close') await store.close();
+ return { activations, textBytes: 9 * 1024 * 1024, ...store.stats };
+ });
+}
+"#;
diff --git a/crates/runtime-host/src/plugins/javascript/remote/tests/retention.rs b/crates/runtime-host/src/plugins/javascript/remote/tests/retention.rs
new file mode 100644
index 0000000000..53d9b27c72
--- /dev/null
+++ b/crates/runtime-host/src/plugins/javascript/remote/tests/retention.rs
@@ -0,0 +1,255 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_js_runtime::plugin::{Bridge, Error as VmError};
+
+#[derive(Default)]
+struct Withdrawals(Mutex<Vec<Value>>);
+impl Bridge for Withdrawals {
+ fn call(&self, method: String, input: Value) -> BoxFuture<'static, Result<Value, VmError>> {
+ assert_eq!(method, "contribution.withdraw");
+ self.0.lock().unwrap().push(input);
+ Box::pin(async { Ok(json!({"ok":true,"value":null})) })
+ }
+}
+
+struct Reader {
+ stream: Box<dyn Stream>,
+ caller: Caller,
+ mount: uuid::Uuid,
+ fence: u64,
+}
+impl Reader {
+ fn query(&self, direction: &str, cursor: Value) -> Value {
+ json!({"resource":"pressure","mount":self.mount,"fence":self.fence,
+ "direction":direction,"cursor":cursor})
+ }
+ async fn close(self, read: &Remote) {
+ let query = self.query("tail", Value::Null);
+ self.stream.close().await.unwrap();
+ assert!(matches!(
+ read.call(query, self.caller).await,
+ Err(Error::Retired)
+ ));
+ }
+}
+
+async fn readers(provider: &Remote, fence: u64) -> Vec<Reader> {
+ let mut readers = Vec::new();
+ for _ in 0..8 {
+ let caller = fixture::caller();
+ let mount = uuid::Uuid::new_v4();
+ let stream = provider
+ .open(
+ json!({"resource":"pressure","mount":mount,
+ "route":null,"locale":"en"}),
+ caller.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ stream.next().await.unwrap().unwrap(),
+ json!({"kind":"ready","fence":fence})
+ );
+ readers.push(Reader {
+ stream,
+ caller,
+ mount,
+ fence,
+ });
+ }
+ readers
+}
+
+async fn page(read: &Remote, reader: &Reader, revision: &str) -> u64 {
+ let first = read
+ .call(reader.query("tail", Value::Null), reader.caller.clone())
+ .await
+ .unwrap();
+ assert_eq!(first["fence"], reader.fence);
+ assert!(serde_json::to_vec(&first).unwrap().len() < 64 * 1024);
+ let records = first["records"].as_array().unwrap();
+ assert!(!records.is_empty());
+ let total = records[0]["total"].as_u64().unwrap();
+ let mut offset = 0;
+ for record in records {
+ assert_eq!(record["kind"], "fragment");
+ assert_eq!(record["revision"], revision);
+ assert_eq!(record["offset"], offset);
+ assert_eq!(record["total"], total);
+ assert!(record["json"].as_str().unwrap().contains('界'));
+ offset += record["json"].as_str().unwrap().len() as u64;
+ }
+ assert!(first["continuation"].is_string());
+ let next = read
+ .call(
+ reader.query("continue", first["continuation"].clone()),
+ reader.caller.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(next["fence"], reader.fence);
+ assert_eq!(next["records"][0]["revision"], revision);
+ assert_eq!(next["records"][0]["offset"], offset);
+ assert!(serde_json::to_vec(&next).unwrap().len() < 64 * 1024);
+ total
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
+async fn large_transcript_history_evicts_old_fences_within_the_real_business_heap() {
+ tokio::time::timeout(Duration::from_secs(30), scenario())
+ .await
+ .unwrap();
+}
+
+async fn scenario() {
+ let limits = Limits::default();
+ assert_eq!(limits.heap_bytes, 128 * 1024 * 1024);
+ let vm = Vm::new(limits).unwrap();
+ let withdrawals = Arc::new(Withdrawals::default());
+ let module = vm
+ .load_plugin(
+ "retention-pressure.mjs".into(),
+ fixture::RETENTION.into(),
+ withdrawals.clone(),
+ )
+ .unwrap();
+ let registrations = module
+ .call(vec!["activate".into()], vec![json!({}), Value::Null])
+ .await
+ .unwrap();
+ let calls = Arc::new(super::super::super::invocation::Calls::new(
+ Default::default(),
+ ));
+ let provider = fixture::remote(&module, ®istrations, &calls, "pressure.stream");
+ let read = fixture::remote(&module, ®istrations, &calls, "pressure.read");
+ let control = fixture::remote(&module, ®istrations, &calls, "control");
+ let oldest = readers(&provider, 0).await;
+ let encoded = page(&read, &oldest[0], "1").await;
+ assert!(encoded > 9 * 1024 * 1024);
+ assert!(encoded * 3 < 32 * 1024 * 1024);
+ assert!(encoded * 4 > 32 * 1024 * 1024);
+ control
+ .call(json!({"kind":"replace","revision":2}), fixture::caller())
+ .await
+ .unwrap();
+ let middle = readers(&provider, 2).await;
+ control
+ .call(json!({"kind":"replace","revision":3}), fixture::caller())
+ .await
+ .unwrap();
+ let recent = readers(&provider, 4).await;
+ let before = control
+ .call(json!({"kind":"stats"}), fixture::caller())
+ .await
+ .unwrap();
+ assert_eq!(before["textBytes"], 9 * 1024 * 1024);
+ assert_eq!(before["active"], 24);
+ assert_eq!(
+ before["invalidated"], 0,
+ "readers share each historical version's byte cost"
+ );
+ let after = control
+ .call(json!({"kind":"replace","revision":4}), fixture::caller())
+ .await
+ .unwrap();
+ assert_eq!(after["activations"], 1);
+ assert_eq!(after["invalidated"], 8);
+ assert_eq!(after["active"], 16);
+ for reader in &oldest {
+ assert_eq!(
+ reader.stream.next().await.unwrap().unwrap(),
+ json!({"kind":"invalidated"})
+ );
+ assert!(reader.stream.next().await.unwrap().is_none());
+ assert!(matches!(
+ read.call(reader.query("tail", Value::Null), reader.caller.clone())
+ .await,
+ Err(Error::Retired)
+ ));
+ }
+ assert_eq!(page(&read, &middle[0], "2").await, encoded);
+ assert_eq!(page(&read, &recent[0], "3").await, encoded);
+ let replacement = recent[0].stream.next().await.unwrap().unwrap();
+ assert_eq!(replacement["kind"], "replace");
+ assert_eq!(replacement["base"], 4);
+ assert_eq!(replacement["revision"], 5);
+ assert_eq!(replacement["record"]["revision"], "4");
+ assert!(serde_json::to_vec(&replacement).unwrap().len() < 64 * 1024);
+ let current = readers(&provider, 6).await;
+ assert_eq!(page(&read, ¤t[0], "4").await, encoded);
+ for reader in oldest
+ .into_iter()
+ .chain(middle)
+ .chain(recent)
+ .chain(current)
+ {
+ reader.close(&read).await;
+ }
+ let empty = control
+ .call(json!({"kind":"stats"}), fixture::caller())
+ .await
+ .unwrap();
+ assert_eq!(empty["active"], 0);
+ assert_eq!(empty["closed"], 32);
+ let reopened = readers(&provider, 6).await;
+ assert_eq!(page(&read, &reopened[0], "4").await, encoded);
+ for reader in reopened {
+ reader.close(&read).await;
+ }
+ for _ in 0..2 {
+ let ended = control
+ .call(json!({"kind":"close"}), fixture::caller())
+ .await
+ .unwrap();
+ assert_eq!(ended["activations"], 1);
+ assert_eq!(ended["active"], 0);
+ assert_eq!(ended["opened"], 40);
+ assert_eq!(ended["closed"], 40);
+ }
+ {
+ let withdrawn = withdrawals.0.lock().unwrap();
+ assert_eq!(
+ withdrawn.len(),
+ 2,
+ "resource close withdraws each registration once"
+ );
+ for (kind, name) in [
+ ("remote_method", "pressure.read"),
+ ("remote_stream", "pressure.stream"),
+ ] {
+ assert!(
+ withdrawn
+ .iter()
+ .any(|value| value == &json!({"kind":kind,"names":[name]}))
+ );
+ }
+ }
+ assert!(
+ !vm.is_terminated(),
+ "large retained sources must fit the unchanged VM heap policy"
+ );
+ drop(provider);
+ drop(read);
+ drop(control);
+ module.close().await.unwrap();
+ assert_eq!(vm.statistics(false).await.unwrap().pending_calls, 0);
+ vm.shutdown().await;
+}
diff --git a/crates/runtime-host/src/server/connection.rs b/crates/runtime-host/src/server/connection.rs
index 987530cca0..fac3b31387 100644
--- a/crates/runtime-host/src/server/connection.rs
+++ b/crates/runtime-host/src/server/connection.rs
@@ -45,6 +45,11 @@ pub(super) struct RequestResidency {
_command: Option<tokio_util::task::task_tracker::TaskTrackerToken>,
}
+struct InFlight {
+ operation: Operation,
+ observation: Option<(Uuid, Uuid)>,
+}
+
enum CompletedRequest {
Reply(PendingReply),
Subscription { active: bool },
@@ -114,7 +119,7 @@ impl Host {
.transpose()?;
let mut requests: FuturesUnordered<BoxFuture<'_, Result<CompletedRequest, HostError>>> =
FuturesUnordered::new();
- let mut in_flight = HashMap::new();
+ let mut in_flight = HashMap::<String, InFlight>::new();
let mut input_open = true;
let result = async {
loop {
@@ -258,18 +263,24 @@ impl Host {
while let Some(id) = outbound.try_flushed() {
in_flight.remove(&id);
}
- // Epoch 141: 64 requests, plus one liveness slot when status occupies
- // either side of that boundary. Reject overload; never stop reading
- // solely because a pending operation is waiting for native input.
- let reserve = in_flight.len() == 64
- && (request.operation == Operation::HostStatus
- || in_flight
- .values()
- .any(|operation| *operation == Operation::HostStatus));
if in_flight.contains_key(&request.request_id) {
return Err("Client reused an active request id".into());
}
- if in_flight.len() >= 64 && !reserve {
+ let authorized = authority.authorizes(&request);
+ let observation = if authorized && request.operation == Operation::PluginRemote {
+ match serde_json::from_value::<maka_protocol::plugin::RemoteRequest>(request.input.clone()) {
+ Ok(maka_protocol::plugin::RemoteRequest::Next { document, stream })
+ if self.plugin_remotes.owns_stream(connection_id, document, stream)
+ && !in_flight.values().any(|active| active.observation == Some((document, stream))) => Some((document, stream)),
+ _ => None,
+ }
+ } else { None };
+ // Owned, unique stream waits do not occupy the finite request lane.
+ // Invalid/duplicate Next requests retain ordinary overload behavior.
+ let finite = in_flight.values().filter(|active| active.observation.is_none()).count();
+ let reserve = finite == maka_protocol::MAX_IN_FLIGHT_DOMAIN_REQUESTS && (request.operation == Operation::HostStatus
+ || in_flight.values().any(|active| active.operation == Operation::HostStatus));
+ if observation.is_none() && finite >= maka_protocol::MAX_IN_FLIGHT_DOMAIN_REQUESTS && !reserve {
return Err("Client exceeded the in-flight request limit".into());
}
// Register before checking admission, with no await between them:
@@ -277,22 +288,18 @@ impl Host {
// A Remote next only awaits delivery from an already owned stream.
// Keep its flush resident, but let retirement cancel idle observers.
let is_observation = request.operation.mode() == maka_protocol::operation::OperationMode::Query
- || (request.operation == Operation::PluginRemote
- && matches!(
- serde_json::from_value::<maka_protocol::plugin::RemoteRequest>(request.input.clone()),
- Ok(maka_protocol::plugin::RemoteRequest::Next { .. })
- ));
+ || observation.is_some();
let mut residency = Some(RequestResidency {
_request: self.requests.token(),
_command: (!is_observation).then(|| self.commands.token()),
});
- in_flight.insert(request.request_id.clone(), request.operation);
+ in_flight.insert(request.request_id.clone(), InFlight { operation: request.operation, observation });
let phase = *self.retirement.lock().unwrap_or_else(|e| e.into_inner());
let draining = phase == super::retirement::Phase::Retiring || self.draining.is_cancelled();
if draining {
residency.take();
}
- let outcome = if !authority.authorizes(&request) {
+ let outcome = if !authorized {
Outcome::failure(OperationError {
code: OperationErrorCode::Unauthorized,
message: "Runtime Host operation is not authorized".into(),
diff --git a/crates/runtime-host/src/server/plugin_remote/registry.rs b/crates/runtime-host/src/server/plugin_remote/registry.rs
index 5e3fe09e9f..c7e20ec546 100644
--- a/crates/runtime-host/src/server/plugin_remote/registry.rs
+++ b/crates/runtime-host/src/server/plugin_remote/registry.rs
@@ -70,7 +70,7 @@ struct DocumentState {
pub(super) struct Reservation {
pub document: Arc<Document>,
id: Uuid,
- _permits: Vec<OwnedSemaphorePermit>,
+ permits: Vec<OwnedSemaphorePermit>,
_task: TaskTrackerToken,
}
impl Default for Registry {
@@ -100,11 +100,6 @@ impl Registry {
let state = connections
.get_mut(&connection)
.ok_or_else(|| failure(Error::Cancelled))?;
- if state.documents.len() >= 32 {
- return Err(failure(Error::Invalid(
- "Remote document limit exceeded".into(),
- )));
- }
let id = Uuid::new_v4();
state.documents.insert(
id,
@@ -142,6 +137,19 @@ impl Registry {
.cloned()
.ok_or_else(|| failure(Error::Cancelled))
}
+ /// Transport scheduling may recognize existing ownership, never create it.
+ pub fn owns_stream(&self, connection: Uuid, document: Uuid, stream: Uuid) -> bool {
+ self.0
+ .connections
+ .lock()
+ .unwrap()
+ .get(&connection)
+ .and_then(|state| state.documents.get(&document))
+ .is_some_and(|document| {
+ let state = document.state.lock().unwrap();
+ !state.closed && state.streams.contains_key(&stream)
+ })
+ }
pub(super) fn close_document(
&self,
connection: Uuid,
@@ -209,7 +217,7 @@ impl Document {
Ok(Reservation {
document: self.clone(),
id,
- _permits: permits,
+ permits,
_task: self.tasks.token(),
})
}
@@ -265,6 +273,12 @@ impl Document {
self.check_cleanup()
}
}
+impl Reservation {
+ /// An opened subscription remains owned, but no longer executes Open work.
+ pub fn release_work(&mut self) {
+ self.permits.clear();
+ }
+}
impl Drop for Reservation {
fn drop(&mut self) {
self.document
diff --git a/crates/runtime-host/src/server/plugin_remote/worker.rs b/crates/runtime-host/src/server/plugin_remote/worker.rs
index b518f4eabc..1990106b2a 100644
--- a/crates/runtime-host/src/server/plugin_remote/worker.rs
+++ b/crates/runtime-host/src/server/plugin_remote/worker.rs
@@ -84,7 +84,7 @@ impl Handle {
}
pub(super) fn start(
- reservation: Reservation,
+ mut reservation: Reservation,
bound: Bound,
provider: Arc<dyn StreamProvider>,
input: Value,
@@ -107,11 +107,18 @@ pub(super) fn start(
reservation.document.insert(id, handle)?;
tasks.spawn(async move {
let _leases = leases;
- let mut result =
- std::panic::AssertUnwindSafe(run(&bound, provider, input, caller, receiver, ready))
- .catch_unwind()
- .await
- .unwrap_or(Err(Error::CleanupUnconfirmed));
+ let mut result = std::panic::AssertUnwindSafe(run(
+ &mut reservation,
+ &bound,
+ provider,
+ input,
+ caller,
+ receiver,
+ ready,
+ ))
+ .catch_unwind()
+ .await
+ .unwrap_or(Err(Error::CleanupUnconfirmed));
stop.cancel();
if resources.finish().await.is_err() {
result = Err(Error::CleanupUnconfirmed);
@@ -132,6 +139,7 @@ pub(super) fn start(
}
async fn run(
+ reservation: &mut Reservation,
bound: &Bound,
provider: Arc<dyn StreamProvider>,
input: Value,
@@ -180,6 +188,7 @@ async fn run(
}
};
drop(opening);
+ reservation.release_work();
let visible = ready.send(Ok(())).is_ok();
let mut terminal = None;
// Keep the provider future across bounded polls: timing out a transport
diff --git a/crates/runtime-host/tests/integration/plugin_remote.rs b/crates/runtime-host/tests/integration/plugin_remote.rs
index 1a7db1ebc6..c991e9347e 100644
--- a/crates/runtime-host/tests/integration/plugin_remote.rs
+++ b/crates/runtime-host/tests/integration/plugin_remote.rs
@@ -43,6 +43,7 @@ mod fixture;
mod import;
mod javascript;
mod mutation_fault;
+mod observations;
mod presenter;
use fixture::{Example, State};
diff --git a/crates/runtime-host/tests/integration/plugin_remote/fixture.rs b/crates/runtime-host/tests/integration/plugin_remote/fixture.rs
index 93d83cf081..62f31704ce 100644
--- a/crates/runtime-host/tests/integration/plugin_remote/fixture.rs
+++ b/crates/runtime-host/tests/integration/plugin_remote/fixture.rs
@@ -36,9 +36,11 @@ use tokio_util::sync::CancellationToken;
pub(super) struct State {
pub(super) views: Mutex<Option<Arc<dyn maka_plugins::remote::Views>>>,
pub(super) calls: AtomicUsize,
+ pub(super) calls_changed: tokio::sync::Notify,
pub(super) opening: AtomicUsize,
pub(super) live: AtomicUsize,
pub(super) reads: AtomicUsize,
+ pub(super) reads_changed: tokio::sync::Notify,
}
struct Adapter(Arc<State>);
pub(super) struct Example {
@@ -174,6 +176,13 @@ impl Method for Adapter {
});
}
self.0.calls.fetch_add(1, Ordering::SeqCst);
+ self.0.calls_changed.notify_one();
+ if input == "blocked" {
+ return Box::pin(async move {
+ caller.cancellation.cancelled().await;
+ Err(Error::Cancelled)
+ });
+ }
*self.0.views.lock().unwrap() = Some(caller.views.clone());
Box::pin(async move {
let response = json!({"input":input,"client":caller.client_instance_id,"session":caller.session_id});
@@ -230,6 +239,7 @@ impl Stream for Events {
_ => {}
}
self.state.reads.fetch_add(1, Ordering::SeqCst);
+ self.state.reads_changed.notify_one();
self.stop.cancelled().await;
Err(Error::Cancelled)
})
diff --git a/crates/runtime-host/tests/integration/plugin_remote/observations.rs b/crates/runtime-host/tests/integration/plugin_remote/observations.rs
new file mode 100644
index 0000000000..997a2b3abb
--- /dev/null
+++ b/crates/runtime-host/tests/integration/plugin_remote/observations.rs
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+
+mod finite;
+use maka_client::{Client, RequestFailure};
+use maka_protocol::{
+ Operation,
+ plugin::{RemoteRequest, RemoteResult},
+};
+
+async fn fixture() -> (ClientFixture, Arc<Host>, Arc<State>, String) {
+ let fixture = ClientFixture::new("maka-observation-lane-");
+ let package = Package::new(BTreeMap::from([
+ (MANIFEST_FILE.into(), serde_json::to_vec(&json!({"schemaVersion":1,"id":"example.remote","client":{"entry":"client.js","sdkVersion":1}})).unwrap()),
+ ("client.js".into(), b"immutable fixture".to_vec()),
+ ])).unwrap();
+ let state = Arc::new(State::default());
+ let mut setup = Setup::default();
+ setup.builtins.insert(
+ "example.remote".into(),
+ Arc::new(Definition {
+ id: "example.remote".into(),
+ revision: package.digest().into(),
+ dependencies: vec![],
+ inject: vec![],
+ plugin: Arc::new(Example {
+ bundle: Bundle::from_package(&package).unwrap().unwrap(),
+ state: state.clone(),
+ }),
+ }),
+ );
+ setup.layers.insert("example.remote".into(), serde_json::from_value(json!([
+ {"type":"insert","rootId":"profile","entry":{"id":"remote-host","packageId":"example.remote"}}
+ ])).unwrap());
+ let host = Host::open_with_options(
+ fixture.owner(),
+ None,
+ HostOptions {
+ plugins: setup,
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ let (mut peer, hello) = Peer::handshake(host.clone(), "observation-inspector").await;
+ ready(&mut peer).await;
+ peer.close().await;
+ (
+ fixture,
+ host,
+ state,
+ hello["hostEpoch"].as_str().unwrap().into(),
+ )
+}
+
+async fn drain(fixture: &ClientFixture, host: Arc<Host>) {
+ #[cfg(unix)]
+ let endpoint = fixture.workspace.parent().unwrap().join("drain.sock");
+ #[cfg(windows)]
+ let endpoint =
+ std::path::PathBuf::from(format!(r"\\.\pipe\maka-drain-{}", uuid::Uuid::new_v4()));
+ let stop = CancellationToken::new();
+ stop.cancel();
+ LocalListener::bind(&endpoint)
+ .unwrap()
+ .serve(host, stop)
+ .await
+ .unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
+async fn owned_idle_next_waits_do_not_exhaust_same_connection_calls_or_close() {
+ tokio::time::timeout(Duration::from_secs(15), async {
+ let (fixture, host, state, epoch) = fixture().await;
+ let (local, remote) = tokio::io::duplex(1024 * 1024);
+ let (reader, writer) = maka_transport::ndjson::split(remote, CancellationToken::new());
+ let serving = tokio::spawn({ let host = host.clone(); async move { host.local_owner_connection(reader, writer).await } });
+ let (client, mut notices) = Client::connect(local, host.root_id(), &epoch, maka_client::Operations).await.unwrap();
+ let observing = tokio::spawn(async move { while notices.recv().await.is_some() {} });
+ let RemoteResult::Document { document } = client.plugin_remote(RemoteRequest::OpenDocument).await.unwrap() else { panic!("document") };
+ let binding: maka_protocol::plugin::RemoteBinding = serde_json::from_value(json!({"packageId":"example.remote","method":"events","sessionId":null})).unwrap();
+ let RemoteResult::Bound { target, .. } = client.plugin_remote(RemoteRequest::Bind { binding: binding.clone() }).await.unwrap() else { panic!("binding") };
+ let mut waits = Vec::new();
+ let mut streams = Vec::new();
+ for _ in 0..96 {
+ let RemoteResult::Opened { stream } = client.plugin_remote(RemoteRequest::Open {
+ binding: binding.clone(), target: target.clone(), document, input: Value::Null,
+ }).await.unwrap() else { panic!("stream") };
+ for _ in 0..2 { assert!(matches!(client.plugin_remote(RemoteRequest::Next { document, stream }).await.unwrap(), RemoteResult::Item { .. })); }
+ let client = client.clone();
+ waits.push(tokio::spawn(async move { client.plugin_remote(RemoteRequest::Next { document, stream }).await }));
+ streams.push(stream);
+ }
+ tokio::time::timeout(Duration::from_secs(3), async {
+ loop {
+ let changed = state.reads_changed.notified();
+ if state.reads.load(Ordering::SeqCst) == 96 { break; }
+ changed.await;
+ }
+ }).await.expect("every owned wait must reach its stream before its ten-second timeout");
+ assert!(waits.iter().all(|wait| !wait.is_finished()));
+ let duplicate = client.plugin_remote(RemoteRequest::Next { document, stream: streams[0] }).await;
+ assert!(matches!(duplicate, Err(RequestFailure::Rejected(_))));
+ let invalid = client.plugin_remote(RemoteRequest::Next { document: uuid::Uuid::new_v4(), stream: streams[0] }).await;
+ assert!(matches!(invalid, Err(RequestFailure::Rejected(_))));
+ let call_binding: maka_protocol::plugin::RemoteBinding = serde_json::from_value(json!({"packageId":"example.remote","method":"echo","sessionId":null})).unwrap();
+ let RemoteResult::Bound { target, .. } = client.plugin_remote(RemoteRequest::Bind { binding: call_binding.clone() }).await.unwrap() else { panic!("method") };
+ let call = client.plugin_remote(RemoteRequest::Call { binding: call_binding, target, document, input: json!("finite") });
+ assert!(matches!(tokio::time::timeout(Duration::from_secs(2), call).await.unwrap().unwrap(), RemoteResult::Value { value } if value["input"] == "finite"));
+ assert_eq!(client.request(Operation::HostWake, json!({})).await.unwrap(), json!({}));
+ assert!(matches!(tokio::time::timeout(Duration::from_secs(2), client.plugin_remote(RemoteRequest::CloseDocument { document })).await.unwrap().unwrap(), RemoteResult::Closed));
+ for wait in waits { assert!(wait.await.unwrap().is_err()); }
+ assert_eq!(state.live.load(Ordering::SeqCst), 0);
+ client.disconnect();
+ serving.await.unwrap().unwrap();
+ observing.await.unwrap();
+ drain(&fixture, host).await;
+ }).await.expect("observation isolation did not settle");
+}
diff --git a/crates/runtime-host/tests/integration/plugin_remote/observations/finite.rs b/crates/runtime-host/tests/integration/plugin_remote/observations/finite.rs
new file mode 100644
index 0000000000..313ded9658
--- /dev/null
+++ b/crates/runtime-host/tests/integration/plugin_remote/observations/finite.rs
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_transport::{MessageReader, MessageWriter, TransportError};
+use std::sync::atomic::AtomicBool;
+use tokio::sync::mpsc;
+
+struct Reader(mpsc::UnboundedReceiver<Value>);
+impl MessageReader for Reader {
+ async fn read(&mut self) -> Result<Option<Value>, TransportError> {
+ Ok(self.0.recv().await)
+ }
+}
+struct Writer {
+ frames: mpsc::UnboundedSender<Value>,
+ pause: Arc<AtomicBool>,
+ entered: CancellationToken,
+}
+impl MessageWriter for Writer {
+ async fn write(&mut self, frame: &Value) -> Result<(), TransportError> {
+ if self.pause.load(Ordering::SeqCst) && frame["requestId"] == "owned-observation" {
+ self.entered.cancel();
+ std::future::pending::<()>().await;
+ }
+ self.frames
+ .send(frame.clone())
+ .map_err(|_| TransportError::Closed)
+ }
+ async fn close_after_flush(&mut self) -> Result<(), TransportError> {
+ Ok(())
+ }
+}
+fn send(sender: &mpsc::UnboundedSender<Value>, id: &str, input: Value) {
+ sender
+ .send(json!({"requestId":id,"operation":"plugin.remote","input":input}))
+ .unwrap();
+}
+async fn rpc(
+ sender: &mpsc::UnboundedSender<Value>,
+ receiver: &mut mpsc::UnboundedReceiver<Value>,
+ input: Value,
+) -> Value {
+ send(sender, "setup", input);
+ loop {
+ let frame = receiver.recv().await.unwrap();
+ if frame["requestId"] == "setup" {
+ return success(frame);
+ }
+ assert!(frame.get("requestId").is_none());
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
+async fn invalid_and_duplicate_next_requests_cannot_bypass_the_finite_flush_budget() {
+ tokio::time::timeout(Duration::from_secs(15), async {
+ for (duplicate, unflushed) in [(false, false), (true, false), (true, true)] {
+ let (fixture, host, state, _) = fixture().await;
+ let (sender, frames) = mpsc::unbounded_channel();
+ let (replies, mut receiver) = mpsc::unbounded_channel();
+ let pause = Arc::new(AtomicBool::new(false));
+ let entered = CancellationToken::new();
+ let connection = tokio::spawn({
+ let host = host.clone();
+ let pause = pause.clone();
+ let entered = entered.clone();
+ async move { host.local_owner_connection(Reader(frames), Writer { frames: replies, pause, entered }).await }
+ });
+ sender.send(json!({"kind":"hello","clientInstanceId":"observation-overload", "protocolMin":0,"protocolMax":0,"compatibilityEpoch":maka_protocol::COMPATIBILITY_EPOCH,"compositionId":maka_protocol::COMPOSITION_ID})).unwrap();
+ let hello = receiver.recv().await.unwrap();
+ assert_eq!(hello["kind"], "accepted");
+ let documents = [
+ rpc(&sender, &mut receiver, json!({"kind":"open_document"})).await["document"].clone(),
+ rpc(&sender, &mut receiver, json!({"kind":"open_document"})).await["document"].clone(),
+ ];
+ let call_binding = json!({"packageId":"example.remote","method":"echo","sessionId":null});
+ let call_target = rpc(&sender, &mut receiver, json!({"kind":"bind","binding":call_binding})).await["target"].clone();
+ let next = if duplicate {
+ let document = &documents[0];
+ let binding = json!({"packageId":"example.remote","method":"events","sessionId":null});
+ let target = rpc(&sender, &mut receiver, json!({"kind":"bind","binding":binding})).await["target"].clone();
+ let stream = rpc(&sender, &mut receiver, json!({"kind":"open","binding":binding,"target":target,"document":document,"input":null})).await["stream"].clone();
+ let next = json!({"kind":"next","document":document,"stream":stream});
+ if unflushed {
+ pause.store(true, Ordering::SeqCst);
+ } else {
+ for _ in 0..2 { rpc(&sender, &mut receiver, next.clone()).await; }
+ }
+ send(&sender, "owned-observation", next.clone());
+ if unflushed {
+ entered.cancelled().await;
+ } else {
+ loop {
+ let changed = state.reads_changed.notified();
+ if state.reads.load(Ordering::SeqCst) == 1 { break; }
+ changed.await;
+ }
+ }
+ next
+ } else {
+ json!({"kind":"next","document":uuid::Uuid::new_v4(),"stream":uuid::Uuid::new_v4()})
+ };
+ // Occupy finite work without producing replies: response capacity
+ // must not race the connection's independent in-flight limit.
+ for index in 0..maka_protocol::MAX_IN_FLIGHT_DOMAIN_REQUESTS {
+ send(&sender, &format!("finite-{index}"), json!({
+ "kind":"call","binding":call_binding,"target":call_target,
+ "document":documents[index % documents.len()],"input":"blocked"
+ }));
+ }
+ loop {
+ let changed = state.calls_changed.notified();
+ if state.calls.load(Ordering::SeqCst) == maka_protocol::MAX_IN_FLIGHT_DOMAIN_REQUESTS { break; }
+ changed.await;
+ }
+ send(&sender, "excess", next);
+ let error = tokio::time::timeout(Duration::from_secs(2), connection).await
+ .expect("invalid Next escaped the ordinary request budget")
+ .unwrap().unwrap_err();
+ assert!(error.to_string().contains("in-flight request limit"), "{error}");
+ assert_eq!(state.live.load(Ordering::SeqCst), 0);
+ drop(sender);
+ drain(&fixture, host).await;
+ }
+ }).await.expect("overload test failed to drain");
+}
diff --git a/crates/runtime-host/tests/integration/plugin_remote/presenter.rs b/crates/runtime-host/tests/integration/plugin_remote/presenter.rs
index 5afac03db7..3cd713a298 100644
--- a/crates/runtime-host/tests/integration/plugin_remote/presenter.rs
+++ b/crates/runtime-host/tests/integration/plugin_remote/presenter.rs
@@ -17,6 +17,7 @@
* under the License.
*/
+mod capacity;
mod fixture;
mod installed;
mod observations;
diff --git a/crates/runtime-host/tests/integration/plugin_remote/presenter/capacity.rs b/crates/runtime-host/tests/integration/plugin_remote/presenter/capacity.rs
new file mode 100644
index 0000000000..25d1382e99
--- /dev/null
+++ b/crates/runtime-host/tests/integration/plugin_remote/presenter/capacity.rs
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use futures_util::future::BoxFuture;
+use maka_plugins::{
+ remote::{Caller, Error, Handler, Method},
+ terminal_ui::{Context, Descriptor, Text},
+};
+use std::sync::atomic::AtomicUsize;
+
+struct Writer(Arc<AtomicUsize>);
+impl Method for Writer {
+ fn call(&self, input: Value, _: Caller) -> BoxFuture<'static, Result<Value, Error>> {
+ assert_eq!(input["kind"], "submit");
+ let count = self.0.fetch_add(1, Ordering::SeqCst) + 1;
+ Box::pin(async move {
+ Ok(json!({"kind":"applied","route":{"operation":input["route"],"writes":count}}))
+ })
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
+async fn idle_documents_and_streams_leave_work_for_calls_receipts_and_close() {
+ tokio::time::timeout(Duration::from_secs(30), scenario())
+ .await
+ .unwrap();
+}
+async fn scenario() {
+ let mut scene = fixture::Scene::new().await;
+ let writes = Arc::new(AtomicUsize::new(0));
+ let publisher = scene.factory.publisher.lock().unwrap().clone().unwrap();
+ let mut staged = Staged::default();
+ staged
+ .insert(
+ "example.pages/write",
+ Endpoint::standalone(Handler::Method(Arc::new(Writer(writes.clone()))))
+ .with_terminal_view(Descriptor::new(Text::plain("Write"), Context::Application))
+ .unwrap(),
+ )
+ .unwrap();
+ let _registration = publisher.publish(staged).unwrap();
+ let (writer, writer_target) = bind(&mut scene.peer, "write").await;
+ let (source, source_target) = bind(&mut scene.peer, "changed").await;
+ let mut documents = Vec::new();
+ let mut pending = Vec::new();
+ for index in 0..65 {
+ let document = document(&mut scene.peer).await;
+ // Cross all previous lifetime thresholds on one connection: >32 docs,
+ // >32 streams on one doc, >128 per connection and >512 Host-wide.
+ for _ in 0..if index == 0 { 40 } else { 8 } {
+ let input = if index == 0 {
+ json!({"route":"pending"})
+ } else {
+ Value::Null
+ };
+ let stream = rpc(
+ &mut scene.peer,
+ json!({"kind":"open","binding":source,
+ "target":source_target,"document":document,"input":input}),
+ )
+ .await["stream"]
+ .clone();
+ if index == 0 {
+ pending.push(stream);
+ }
+ }
+ documents.push(document);
+ }
+ assert_eq!(scene.factory.sources.opened.load(Ordering::SeqCst), 552);
+ assert_eq!(scene.factory.sources.closed.load(Ordering::SeqCst), 0);
+ let first = &documents[0];
+ for (index, stream) in pending.iter().enumerate() {
+ scene.peer.send_rpc(
+ &format!("idle-{index}"),
+ "plugin.remote",
+ json!({"kind":"next","document":first,"stream":stream}),
+ );
+ }
+ scene
+ .factory
+ .sources
+ .next_entered
+ .acquire_many(40)
+ .await
+ .unwrap()
+ .forget();
+ let mut submit = call(&writer, &writer_target, first, "original-operation");
+ submit["input"] = json!({"kind":"submit","route":"original-operation","revision":"1","action":"save","fields":{},"locale":"en"});
+ let receipt = rpc(&mut scene.peer, submit).await["value"].clone();
+ assert_eq!(
+ receipt,
+ json!({"kind":"applied","route":{"operation":"original-operation","writes":1}})
+ );
+ assert_eq!(writes.load(Ordering::SeqCst), 1);
+ // A single-stream close and whole-document close do not compete for work
+ // permits held by a sleeping provider or abandon its original Next future.
+ scene.peer.send_rpc(
+ "close-one",
+ "plugin.remote",
+ json!({"kind":"close","document":first,"stream":pending[0]}),
+ );
+ let replies = [
+ response(&mut scene.peer).await,
+ response(&mut scene.peer).await,
+ ];
+ assert!(
+ replies
+ .iter()
+ .any(|reply| reply["requestId"] == "close-one" && reply["ok"] == true)
+ );
+ assert!(
+ replies.iter().any(|reply| reply["requestId"] == "idle-0"
+ && reply["error"]["code"] == "operation_conflict")
+ );
+ scene.peer.send_rpc(
+ "close-first",
+ "plugin.remote",
+ json!({"kind":"close_document","document":first}),
+ );
+ for _ in 0..40 {
+ let reply = response(&mut scene.peer).await;
+ if reply["requestId"] == "close-first" {
+ assert_eq!(reply["ok"], true, "{reply}");
+ } else {
+ assert!(reply["requestId"].as_str().unwrap().starts_with("idle-"));
+ assert_eq!(reply["error"]["code"], "operation_conflict", "{reply}");
+ }
+ }
+ for document in &documents[1..] {
+ rpc(
+ &mut scene.peer,
+ json!({"kind":"close_document","document":document}),
+ )
+ .await;
+ }
+ assert_eq!(scene.factory.sources.closed.load(Ordering::SeqCst), 552);
+ assert_eq!(writes.load(Ordering::SeqCst), 1);
+ business(&mut scene.peer).await;
+ assert_eq!(bind(&mut scene.peer, "write").await.1, writer_target);
+ scene.close().await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
+async fn calls_waiting_on_a_source_leave_its_owned_next_and_close_runnable() {
+ tokio::time::timeout(Duration::from_secs(15), async {
+ let mut scene = fixture::Scene::new().await;
+ let (method, target) = bind(&mut scene.peer, "activity-read").await;
+ let (source, source_target) = bind(&mut scene.peer, "changed").await;
+ let document = document(&mut scene.peer).await;
+ let stream = rpc(
+ &mut scene.peer,
+ json!({"kind":"open","binding":source,
+ "target":source_target,"document":document,"input":"release-dependent-calls"}),
+ )
+ .await["stream"]
+ .clone();
+ let request = json!({"kind":"call","binding":method,"target":target,
+ "document":document,"input":{"waitForSource":true}});
+ for index in 0..32 {
+ scene.peer.send_rpc(
+ &format!("dependent-{index}"),
+ "plugin.remote",
+ request.clone(),
+ );
+ }
+ // All ordinary document permits are held by admitted calls whose actual
+ // result depends on the source; another ordinary Call must still reject.
+ scene
+ .factory
+ .sources
+ .calls_waiting
+ .acquire_many(32)
+ .await
+ .unwrap()
+ .forget();
+ assert_eq!(
+ scene.peer.rpc("plugin.remote", request).await["error"]["code"],
+ "invalid_request"
+ );
+ assert_eq!(scene.factory.sources.reads.load(Ordering::SeqCst), 32);
+ scene.peer.send_rpc(
+ "deliver",
+ "plugin.remote",
+ json!({"kind":"next","document":document,"stream":stream}),
+ );
+ let mut completed = std::collections::HashSet::new();
+ for _ in 0..33 {
+ let reply = response(&mut scene.peer).await;
+ assert_eq!(reply["ok"], true, "{reply}");
+ let id = reply["requestId"].as_str().unwrap();
+ assert!(completed.insert(id.to_owned()));
+ if id == "deliver" {
+ assert_eq!(reply["result"]["item"], "release-dependent-calls");
+ } else {
+ assert!(id.starts_with("dependent-"));
+ assert_eq!(reply["result"]["value"]["document"], document);
+ }
+ }
+ assert!(completed.contains("deliver"));
+ rpc(
+ &mut scene.peer,
+ json!({"kind":"close","document":document,"stream":stream}),
+ )
+ .await;
+ rpc(
+ &mut scene.peer,
+ json!({"kind":"close_document","document":document}),
+ )
+ .await;
+ assert_eq!(scene.factory.sources.closed.load(Ordering::SeqCst), 1);
+ scene.close().await;
+ })
+ .await
+ .unwrap();
+}
diff --git a/crates/runtime-host/tests/integration/plugin_remote/presenter/sources.rs b/crates/runtime-host/tests/integration/plugin_remote/presenter/sources.rs
index c8344e0902..f8bcc5fd0f 100644
--- a/crates/runtime-host/tests/integration/plugin_remote/presenter/sources.rs
+++ b/crates/runtime-host/tests/integration/plugin_remote/presenter/sources.rs
@@ -40,6 +40,9 @@ pub(super) struct Sources {
pub closed: AtomicUsize,
pub reads: AtomicUsize,
pub completed: Semaphore,
+ pub next_entered: Semaphore,
+ pub calls_waiting: Arc<Semaphore>,
+ delivered: Arc<Semaphore>,
}
impl Default for Sources {
fn default() -> Self {
@@ -48,6 +51,9 @@ impl Default for Sources {
closed: AtomicUsize::new(0),
reads: AtomicUsize::new(0),
completed: Semaphore::new(0),
+ next_entered: Semaphore::new(0),
+ calls_waiting: Arc::new(Semaphore::new(0)),
+ delivered: Arc::new(Semaphore::new(0)),
}
}
}
@@ -97,7 +103,18 @@ impl Sources {
impl Method for Sources {
fn call(&self, input: Value, caller: Caller) -> BoxFuture<'static, Result<Value, Error>> {
self.reads.fetch_add(1, Ordering::SeqCst);
- Box::pin(async move { Ok(json!({"input":input,"document":caller.document_id})) })
+ let waiting = self.calls_waiting.clone();
+ let delivered = self.delivered.clone();
+ Box::pin(async move {
+ if input.get("waitForSource").and_then(Value::as_bool) == Some(true) {
+ waiting.add_permits(1);
+ tokio::select! {
+ _ = caller.cancellation.cancelled() => return Err(Error::Cancelled),
+ permit = delivered.acquire() => permit.unwrap().forget(),
+ }
+ }
+ Ok(json!({"input":input,"document":caller.document_id}))
+ })
}
}
struct Provider(Arc<Sources>);
@@ -125,7 +142,17 @@ struct Instance {
}
impl Stream for Instance {
fn next(&self) -> BoxFuture<'_, Result<Option<Value>, Error>> {
- Box::pin(async { Ok(Some(self.input.clone())) })
+ Box::pin(async {
+ if self.input == "release-dependent-calls" {
+ self.state.delivered.add_permits(32);
+ }
+ if self.input.get("route").and_then(Value::as_str) == Some("pending") {
+ self.state.next_entered.add_permits(1);
+ self.source.cancelled().await;
+ return Err(Error::Cancelled);
+ }
+ Ok(Some(self.input.clone()))
+ })
}
fn cancel(&self) {
self.source.cancel();
diff --git a/crates/tui/locales/en.ftl b/crates/tui/locales/en.ftl
index 10250a6751..9b9193501f 100644
--- a/crates/tui/locales/en.ftl
+++ b/crates/tui/locales/en.ftl
@@ -957,7 +957,6 @@ sidebar-title = Sessions
sidebar-all = All
sidebar-pending = Needs you
-transcript-capacity = Too many readers are open. Close another view to read this one.
transcript-failed = This reader could not be updated.
transcript-buffer-full = The reader reached its local capacity.
transcript-expired = This reader has expired.
diff --git a/crates/tui/locales/zh-CN.ftl b/crates/tui/locales/zh-CN.ftl
index 97a1d2e955..712cd5d752 100644
--- a/crates/tui/locales/zh-CN.ftl
+++ b/crates/tui/locales/zh-CN.ftl
@@ -957,7 +957,6 @@ sidebar-title = 会话
sidebar-all = 全部
sidebar-pending = 待处理
-transcript-capacity = 打开的阅读区过多。关闭另一视图后可在此阅读。
transcript-failed = 此阅读区无法更新。
transcript-buffer-full = 阅读区已达到本地容量上限。
transcript-expired = 此阅读区的数据已过期。
diff --git a/crates/tui/locales/zh-TW.ftl b/crates/tui/locales/zh-TW.ftl
index 8ad692dfc6..8254f2addf 100644
--- a/crates/tui/locales/zh-TW.ftl
+++ b/crates/tui/locales/zh-TW.ftl
@@ -957,7 +957,6 @@ sidebar-title = 對話
sidebar-all = 全部
sidebar-pending = 待處理
-transcript-capacity = 開啟的閱讀區過多。關閉另一檢視後可在此閱讀。
transcript-failed = 此閱讀區無法更新。
transcript-buffer-full = 閱讀區已達本機容量上限。
transcript-expired = 此閱讀區的資料已過期。
diff --git a/crates/tui/src/app.rs b/crates/tui/src/app.rs
index 9b8a5315c4..fa029ea838 100644
--- a/crates/tui/src/app.rs
+++ b/crates/tui/src/app.rs
@@ -183,6 +183,7 @@ pub struct App {
pub status: Option<Value>,
pub notice: Option<Notice>,
pub state_error: Option<String>,
+ pub(crate) checkpoint_budget: crate::state::Budget,
pub closing: bool,
pub shutdown: crate::shutdown::State,
pub theme: crate::theme::Theme,
@@ -239,6 +240,7 @@ impl App {
status: None,
notice: None,
state_error: None,
+ checkpoint_budget: Default::default(),
closing: false,
shutdown: Default::default(),
theme: crate::theme::Theme::default(),
@@ -424,6 +426,7 @@ impl App {
return known == root;
}
self.known_root = Some(root.into());
+ self.checkpoint_changed(crate::state::Impact::Other);
true
}
pub(crate) fn checkpoint_root(&self) -> &str {
@@ -567,6 +570,9 @@ impl App {
if !self.enabled(&action) {
return None;
}
+ if !matches!(action, Action::Apps(_)) {
+ self.checkpoint_changed(crate::state::Impact::Other);
+ }
match action {
Action::Inbox => {
self.palette = None;
@@ -1061,7 +1067,7 @@ impl App {
_ => navigation.visit(target.clone()),
}
let view_focus = matches!(intent, Intent::ChangeView { .. }).then_some(self.focus);
- if !self.admit_state(Some((&navigation, true, view_focus)), 0)
+ if !self.admit_state(Some((&navigation, true, view_focus)))
|| !self.prepare_route(&target.route)
{
return;
@@ -1224,6 +1230,8 @@ impl App {
/// Only the displayed frame contributes hit regions. Overlay rendering
/// replaces that list, so a mouse event cannot reach a covered page.
pub fn input(&mut self, event: Event) -> (bool, Option<Action>) {
+ self.checkpoint_input(crate::state::Impact::Other);
+ let checkpoint_focus = self.focus;
if self.shutdown.stopping
&& !matches!(
event,
@@ -1309,6 +1317,10 @@ impl App {
self.hover_area = None;
self.hover_since = None;
}
+ if self.focus != checkpoint_focus {
+ self.checkpoint_input(crate::state::Impact::Other);
+ }
+ self.checkpoint_changed(self.checkpoint_input_impact());
outcome
}
diff --git a/crates/tui/src/apps.rs b/crates/tui/src/apps.rs
index 902675023b..8c7f5c3c25 100644
--- a/crates/tui/src/apps.rs
+++ b/crates/tui/src/apps.rs
@@ -580,6 +580,7 @@ impl App {
requests
}
pub fn apps_complete(&mut self, request: Request, result: Result<Output, io::Failure>) {
+ self.checkpoint_changed(crate::state::Impact::Other);
if !matches!(&self.connection,
ConnectionState::Connected { root_id, epoch } if *root_id == request.root && *epoch == request.epoch)
{
@@ -620,12 +621,16 @@ impl App {
reply: Reply::View { view },
}) if reloading => {
instance.live = Some(entry.target.clone());
- if instance.keeps() {
- instance.reload_draft(*entry, view, &request.root);
+ let automatic = if instance.keeps() {
+ instance.reload_draft(*entry, view)
} else {
instance.entry = Some(*entry);
instance.install(view);
instance.message = None;
+ false
+ };
+ if automatic {
+ self.accept_app_draft(&key);
}
self.mount_app_views();
return;
@@ -1062,8 +1067,13 @@ impl App {
if !self.apps_enabled(&message) {
return None;
}
+ if !matches!(
+ &message,
+ Message::Instance(_, Command::View(Intent::Toggle(_) | Intent::Pick(_, _)))
+ ) {
+ self.checkpoint_changed(crate::state::Impact::Other);
+ }
let locale = self.apps.locale.clone();
- let root = self.checkpoint_root().to_owned();
let (key, command) = match message {
Message::Directory => {
if self.apps.loaded && !self.apps.listing {
@@ -1128,6 +1138,12 @@ impl App {
{
return None;
}
+ if matches!(command, Command::ApplyDraft) {
+ if self.accept_app_draft(&key) {
+ self.mount_app_views();
+ }
+ return None;
+ }
let apps = &mut self.apps;
let replacement = matches!(command, Command::Discard | Command::ConfirmDiscard)
.then(|| apps.entry(&key).cloned())
@@ -1150,11 +1166,7 @@ impl App {
},
});
}
- Command::ApplyDraft => {
- if instance.accept_draft(&root) {
- self.mount_app_views();
- }
- }
+ Command::ApplyDraft => unreachable!("draft admission handled before mutation"),
Command::CancelDraft => {
instance.review = None;
instance.message = Some(Notice::Local("extensions-restored"));
diff --git a/crates/tui/src/apps/admission.rs b/crates/tui/src/apps/admission.rs
index a81564d925..eec50c9428 100644
--- a/crates/tui/src/apps/admission.rs
+++ b/crates/tui/src/apps/admission.rs
@@ -20,12 +20,18 @@
use super::*;
impl Apps {
+ #[cfg(test)]
pub(crate) fn kept_count(&self) -> usize {
self.instances
.values()
.filter(|instance| instance.keeps())
.count()
}
+ pub(crate) fn reserves_checkpoint(&self, key: &Key) -> bool {
+ self.instances.get(key).is_some_and(|instance| {
+ instance.unresolved.is_some() || instance.writing || instance.saving
+ })
+ }
}
impl Instance {
@@ -58,6 +64,26 @@ impl Instance {
}
impl App {
+ pub(super) fn accept_app_draft(&mut self, key: &Key) -> bool {
+ let candidate = self
+ .apps
+ .instances
+ .get(key)
+ .and_then(|instance| instance.draft_checkpoint(self.checkpoint_root()));
+ let accepted = candidate.as_ref().is_some_and(|(checkpoint, kept)| {
+ self.admit_checkpoint(key, kept.then_some(checkpoint), false)
+ });
+ let root = self.checkpoint_root().to_owned();
+ let Some(instance) = self.apps.instances.get_mut(key) else {
+ return false;
+ };
+ if !accepted {
+ instance.message = Some(Notice::Local("extensions-capacity"));
+ return false;
+ }
+ instance.accept_draft(&root)
+ }
+
pub(super) fn admit_field(&mut self, key: &Key, field: &str, value: &Value) -> bool {
let Some(instance) = self.apps.instances.get(key) else {
return false;
@@ -65,11 +91,32 @@ impl App {
if instance.drafts.get(field) == Some(value) {
return true;
}
- let first = !instance.keeps();
- let accepted = instance
+ let kept = instance.blocked
+ || instance.unresolved.is_some()
+ || instance.writing
+ || instance.result.is_some()
+ || instance.view.as_ref().is_some_and(|view| {
+ view.fields.iter().any(|item| {
+ let proposed = if item.id == field {
+ Some(value)
+ } else {
+ instance.drafts.get(&item.id)
+ };
+ proposed != Some(&drafts::value(&item.control))
+ })
+ });
+ let reserved = self.apps.reserves_checkpoint(key);
+ let checkpoint = instance
.checkpoint(self.checkpoint_root(), key, None)
- .is_some_and(|mut checkpoint| checkpoint.admit_field(field, value, &instance.drafts));
- if !accepted || first && !self.admit_state(None, 1) {
+ .and_then(|mut checkpoint| {
+ checkpoint
+ .admit_field(field, value, &instance.drafts)
+ .then_some(checkpoint)
+ });
+ let accepted = checkpoint.as_ref().is_some_and(|checkpoint| {
+ self.admit_checkpoint(key, kept.then_some(checkpoint), reserved)
+ });
+ if !accepted {
self.apps.instances.get_mut(key).unwrap().message =
Some(Notice::Local("extensions-capacity"));
return false;
@@ -82,7 +129,7 @@ impl App {
}
/// Validate every newly frozen write before changing generation, saving or
- /// unresolved identity. Earlier accepted candidates reserve their slot too.
+ /// unresolved identity. Earlier accepted writes reserve their result bytes too.
pub(super) fn admit_pending_writes(&mut self) {
let candidates: Vec<_> = self
.apps
@@ -100,17 +147,17 @@ impl App {
return None;
}
let pending = instance.frozen_pending(instance.pending.as_ref()?)?;
- Some((key.clone(), pending, !instance.keeps()))
+ Some((key.clone(), pending))
})
.collect();
- let mut additions = 0;
- for (key, pending, first) in candidates {
- let local = self.apps.instances[&key]
+ for (key, pending) in candidates {
+ let checkpoint = self.apps.instances[&key]
.checkpoint(self.checkpoint_root(), &key, Some(&pending))
- .is_some_and(|checkpoint| checkpoint.admit_cursors());
- if local && self.admit_state(None, additions + usize::from(first)) {
- additions += usize::from(first);
- } else {
+ .filter(|checkpoint| checkpoint.capacity_bytes().is_some());
+ if !checkpoint
+ .as_ref()
+ .is_some_and(|checkpoint| self.admit_checkpoint(&key, Some(checkpoint), true))
+ {
let instance = self.apps.instances.get_mut(&key).unwrap();
instance.pending = None;
instance.message = Some(Notice::Local("extensions-capacity"));
diff --git a/crates/tui/src/apps/admission/tests.rs b/crates/tui/src/apps/admission/tests.rs
index ea1bda405b..bda244ea73 100644
--- a/crates/tui/src/apps/admission/tests.rs
+++ b/crates/tui/src/apps/admission/tests.rs
@@ -24,7 +24,7 @@ use serde_json::json;
fn fill(app: &mut App) {
let entry = instance(app).entry.clone().unwrap();
- for index in 0..32 {
+ for index in 0..64 {
let key = key().at(json!({"kept": index}));
let mut retained = Instance::new(Some(entry.clone()), key.clone());
retained.install(form());
@@ -58,11 +58,11 @@ fn fill(app: &mut App) {
}
app.apps.instances.insert(key, retained);
}
- assert_eq!(app.apps.kept_count(), 32);
+ assert_eq!(app.apps.kept_count(), 64);
}
#[test]
-fn thirty_third_owner_refuses_typing_toggle_and_freeze_without_changing_the_original() {
+fn many_small_retained_owners_admit_typing_toggle_and_freeze_without_changing_others() {
let mut app = app();
fill(&mut app);
let retained = serde_json::to_vec(&app.apps.checkpoints("root")).unwrap();
@@ -73,29 +73,32 @@ fn thirty_third_owner_refuses_typing_toggle_and_freeze_without_changing_the_orig
KeyCode::Char('a'),
KeyModifiers::CONTROL,
)));
- let cursor = instance(&app).editors["name"].cursor();
- let history = instance(&app).editors["name"].retained_bytes();
- app.input(Event::Paste("refused draft".into()));
- assert_eq!(instance(&app).editors["name"].text(), "My notes");
- assert_eq!(instance(&app).editors["name"].cursor(), cursor);
- assert_eq!(instance(&app).editors["name"].retained_bytes(), history);
+ app.input(Event::Paste("accepted draft".into()));
+ assert_eq!(instance(&app).editors["name"].text(), "accepted draft");
app.apps_action(command(Command::View(Intent::Toggle("enabled".into()))));
- assert_eq!(instance(&app).drafts["enabled"], json!(true));
+ assert_eq!(instance(&app).drafts["enabled"], json!(false));
let generation = instance(&app).generation;
app.apps_action(save());
- assert!(next(&mut app).is_none());
- assert_eq!(instance(&app).generation, generation);
- assert!(instance(&app).unresolved.is_none());
- assert!(!instance(&app).saving);
+ assert!(next(&mut app).unwrap().needs_checkpoint());
+ assert!(instance(&app).generation > generation);
+ assert!(instance(&app).unresolved.is_some());
+ assert!(instance(&app).saving);
assert_eq!(serde_json::to_vec(&app.navigation).unwrap(), navigation);
assert_eq!(
- serde_json::to_vec(&app.apps.checkpoints("root")).unwrap(),
+ serde_json::to_vec(
+ &app.apps
+ .checkpoints("root")
+ .into_iter()
+ .filter(|checkpoint| checkpoint.address() != &key())
+ .collect::<Vec<_>>()
+ )
+ .unwrap(),
retained
);
}
#[test]
-fn authorization_also_reserves_before_freezing_a_clean_owner() {
+fn authorization_reserves_result_bytes_after_more_than_thirty_two_retained_owners() {
use maka_plugins::authorization::{Capability, Request as Proposal, Target};
let mut app = app();
app.apps_action(save());
@@ -116,10 +119,10 @@ fn authorization_also_reserves_before_freezing_a_clean_owner() {
assert!(app.apps_enabled(&command(Command::ApproveConsent)));
let generation = instance(&app).generation;
app.apps_action(command(Command::ApproveConsent));
- assert!(next(&mut app).is_none());
- assert_eq!(instance(&app).generation, generation);
- assert!(instance(&app).unresolved.is_none());
- assert!(!instance(&app).busy);
+ assert!(next(&mut app).unwrap().needs_checkpoint());
+ assert!(instance(&app).generation > generation);
+ assert!(instance(&app).unresolved.is_some());
+ assert!(instance(&app).busy);
}
#[test]
@@ -143,3 +146,30 @@ fn local_growth_counts_json_escapes_and_keeps_the_existing_draft() {
assert!(!app.admit_field(&key(), "name", &json!("\\\"".repeat(1800))));
assert_eq!(instance(&app).drafts["name"], json!("first"));
}
+
+#[test]
+fn consecutive_field_edits_and_selection_only_recalculate_the_owner() {
+ let mut app = app();
+ fill(&mut app);
+ draw(&mut app, 90, 28);
+ instance_mut(&mut app).surface.focus(NAME.into());
+ app.input(Event::Paste(" warm".into()));
+ let before = App::admission_checks();
+ for _ in 0..8 {
+ app.input(Event::Key(KeyEvent::new(
+ KeyCode::Char('a'),
+ KeyModifiers::NONE,
+ )));
+ app.input(Event::Key(KeyEvent::new(
+ KeyCode::Left,
+ KeyModifiers::SHIFT,
+ )));
+ app.input(Event::Key(KeyEvent::new(
+ KeyCode::Right,
+ KeyModifiers::NONE,
+ )));
+ assert!(app.apps_requests().is_empty());
+ }
+ assert_eq!(App::admission_checks(), before);
+ assert!(instance(&app).editors["name"].text().contains("warm"));
+}
diff --git a/crates/tui/src/apps/drafts.rs b/crates/tui/src/apps/drafts.rs
index 3b09110dc9..c64a92b1f2 100644
--- a/crates/tui/src/apps/drafts.rs
+++ b/crates/tui/src/apps/drafts.rs
@@ -99,22 +99,19 @@ impl Instance {
all_drafts.validate().map_err(|_| ())?;
Ok(review)
}
- pub fn reload_draft(&mut self, entry: TerminalViewProjection, view: View, root: &str) {
+ pub fn reload_draft(&mut self, entry: TerminalViewProjection, view: View) -> bool {
self.blocked = true;
let Ok(review) = self.merge(entry, view) else {
self.message = Some(Notice::Local("extensions-draft-shape-changed"));
- return;
+ return false;
};
let changed = self
.view
.as_ref()
.is_some_and(|old| context_changed(old, &review.view));
self.review = Some(review);
- if !changed && self.review.as_ref().unwrap().conflicts.is_empty() {
- self.accept_draft(root);
- } else {
- self.message = None;
- }
+ self.message = None;
+ !changed && self.review.as_ref().unwrap().conflicts.is_empty()
}
pub fn accept_draft(&mut self, root: &str) -> bool {
if self.review.is_some() && !self.draft_fits(root) {
diff --git a/crates/tui/src/apps/drafts/admission.rs b/crates/tui/src/apps/drafts/admission.rs
index f059eb9040..6d799b5aab 100644
--- a/crates/tui/src/apps/drafts/admission.rs
+++ b/crates/tui/src/apps/drafts/admission.rs
@@ -21,9 +21,15 @@ use super::*;
impl Instance {
pub(super) fn draft_fits(&self, root: &str) -> bool {
- let Some(review) = &self.review else {
- return false;
- };
+ self.draft_checkpoint(root)
+ .is_some_and(|(checkpoint, _)| checkpoint.capacity_bytes().is_some())
+ }
+
+ pub(in crate::apps) fn draft_checkpoint(
+ &self,
+ root: &str,
+ ) -> Option<(saved::Checkpoint, bool)> {
+ let review = self.review.as_ref()?;
let mut candidate = Instance::new(Some(review.entry.clone()), self.address.clone());
candidate.install(review.view.clone());
candidate.drafts = review.values.clone();
@@ -37,13 +43,12 @@ impl Instance {
for (id, editor) in &mut candidate.editors {
let initial = editor.text().to_owned();
editor.clear_if_unchanged(&initial);
- let Some(text) = candidate.drafts.get(id).and_then(Value::as_str) else {
- return false;
- };
+ let text = candidate.drafts.get(id).and_then(Value::as_str)?;
editor.insert(text);
}
+ let kept = candidate.keeps();
candidate
.checkpoint(root, &self.address, None)
- .is_some_and(|checkpoint| checkpoint.admit_cursors())
+ .map(|checkpoint| (checkpoint, kept))
}
}
diff --git a/crates/tui/src/apps/io/transcript.rs b/crates/tui/src/apps/io/transcript.rs
index 887f633f54..0f87b1eb06 100644
--- a/crates/tui/src/apps/io/transcript.rs
+++ b/crates/tui/src/apps/io/transcript.rs
@@ -39,7 +39,6 @@ use std::{
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;
-pub const MAX_MOUNTS: usize = 4;
const DELIVERY_CAPACITY: usize = 32;
/// The token is allocated locally for the full source/route/node binding.
@@ -192,7 +191,7 @@ mod tests {
use super::test_peer::mount;
#[test]
- fn mount_admission_rejects_duplicate_rebound_and_excess_tokens() {
+ fn mount_admission_accepts_many_readers_but_rejects_duplicate_or_rebound_tokens() {
let (mut runner, _deliveries) = Runner::new();
let mount = mount();
assert_eq!(runner.admit(std::slice::from_ref(&mount)), Ok(()));
@@ -200,10 +199,15 @@ mod tests {
runner.admit(&[mount.clone(), mount.clone()]),
Err(Failure::Invalid)
);
- assert_eq!(
- runner.admit(&vec![mount.clone(); MAX_MOUNTS + 1]),
- Err(Failure::Overflow)
- );
+ let readers: Vec<_> = (0..64)
+ .map(|_| Mount {
+ token: Uuid::new_v4(),
+ ..mount.clone()
+ })
+ .collect();
+ for count in [5, 32, 33, 64] {
+ assert_eq!(runner.admit(&readers[..count]), Ok(()));
+ }
let (commands, _receiver) = mpsc::channel(1);
let (stop, _stopped) = oneshot::channel();
runner.running.insert(
diff --git a/crates/tui/src/apps/io/transcript/runner.rs b/crates/tui/src/apps/io/transcript/runner.rs
index b08d6795b2..1abfc9cd80 100644
--- a/crates/tui/src/apps/io/transcript/runner.rs
+++ b/crates/tui/src/apps/io/transcript/runner.rs
@@ -102,9 +102,6 @@ impl Runner {
}
pub(super) fn admit(&self, wanted: &[Mount]) -> Result<(), Failure> {
- if wanted.len() > MAX_MOUNTS {
- return Err(Failure::Overflow);
- }
let mut tokens = HashSet::new();
for mount in wanted {
if !tokens.insert(mount.token)
diff --git a/crates/tui/src/apps/mount.rs b/crates/tui/src/apps/mount.rs
index baf26d5079..d6e8d0bc88 100644
--- a/crates/tui/src/apps/mount.rs
+++ b/crates/tui/src/apps/mount.rs
@@ -94,8 +94,7 @@ impl App {
location.embedded.sort_by_key(Key::depth);
if &location != self.navigation.location() {
let mut navigation = self.navigation.clone();
- if !navigation.replace(location)
- || !self.admit_state(Some((&navigation, false, None)), 0)
+ if !navigation.replace(location) || !self.admit_state(Some((&navigation, false, None)))
{
return;
}
diff --git a/crates/tui/src/apps/region.rs b/crates/tui/src/apps/region.rs
index 589984788c..4bb535cddc 100644
--- a/crates/tui/src/apps/region.rs
+++ b/crates/tui/src/apps/region.rs
@@ -92,6 +92,7 @@ pub(super) fn input<M: Clone>(
if let Some(redraw) =
super::transcript::input(&mut apps.readers, surface, event, keyboard, ascii)
{
+ app.checkpoint_input(crate::state::Impact::Reading);
return Some(redraw);
}
let enabled = |apps: &Apps, well: &Well| {
@@ -128,6 +129,7 @@ pub(super) fn input<M: Clone>(
if press {
surface.focus(well.path.clone());
}
+ app.checkpoint_input(crate::state::Impact::Reading);
return Some(changed || press);
}
if !keyboard {
@@ -177,6 +179,7 @@ pub(super) fn input<M: Clone>(
_ => return None,
};
let edits_text = proposed.is_some();
+ app.checkpoint_input(crate::state::Impact::Reading);
if let Some(text) = proposed
&& !app.admit_field(&well.key, &well.field, &Value::String(text))
{
diff --git a/crates/tui/src/apps/saved/admission.rs b/crates/tui/src/apps/saved/admission.rs
index 82330b40bc..3a5438acc1 100644
--- a/crates/tui/src/apps/saved/admission.rs
+++ b/crates/tui/src/apps/saved/admission.rs
@@ -23,6 +23,18 @@ use super::*;
mod tests;
impl Checkpoint {
+ pub(crate) fn capacity_bytes(&self) -> Option<usize> {
+ self.validate(&self.root).ok()?;
+ let mut bytes = serde_json::to_vec(self).ok()?.len();
+ for (id, cursor) in &self.cursors {
+ let text = self.drafts.get(id)?.as_str()?;
+ bytes = bytes
+ .checked_sub(serde_json::to_vec(cursor).ok()?.len())?
+ .checked_add(serde_json::to_vec(&Cursor::largest(text)).ok()?.len())?;
+ }
+ (bytes <= MAX_BYTES).then_some(bytes)
+ }
+
pub(in crate::apps) fn admit_field(
&mut self,
id: &str,
@@ -67,6 +79,7 @@ impl Checkpoint {
self.admit_cursors_ref()
}
+ #[cfg(test)]
pub(in crate::apps) fn admit_cursors(mut self) -> bool {
self.admit_cursors_ref()
}
diff --git a/crates/tui/src/apps/transcript/runtime.rs b/crates/tui/src/apps/transcript/runtime.rs
index 1f983c3f3b..fcb5b3eedb 100644
--- a/crates/tui/src/apps/transcript/runtime.rs
+++ b/crates/tui/src/apps/transcript/runtime.rs
@@ -62,8 +62,6 @@ impl App {
));
}
}
- // Resource allocation is bounded across every placement, including slots.
- wanted.truncate(4);
self.apps.readers.mounts.retain(|identity, mount| {
let Some((_, _, _, observing)) =
wanted.iter().find(|(key, route, binding, observing)| {
diff --git a/crates/tui/src/apps/transcript/tests.rs b/crates/tui/src/apps/transcript/tests.rs
index a308c4eaf4..56842d99af 100644
--- a/crates/tui/src/apps/transcript/tests.rs
+++ b/crates/tui/src/apps/transcript/tests.rs
@@ -449,3 +449,5 @@ fn a_page_received_during_selection_stays_static_and_pauses_after_projection() {
}
mod retained;
+
+mod capacity;
diff --git a/crates/tui/src/apps/transcript/tests/capacity.rs b/crates/tui/src/apps/transcript/tests/capacity.rs
new file mode 100644
index 0000000000..863fbd4461
--- /dev/null
+++ b/crates/tui/src/apps/transcript/tests/capacity.rs
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use std::collections::BTreeSet;
+
+fn populated(count: usize) -> App {
+ let mut app = app();
+ let view = View {
+ version: VERSION,
+ title: "Reader capacity".into(),
+ revision: "original".into(),
+ fields: vec![],
+ actions: vec![],
+ root: Node::Column {
+ key: "root".into(),
+ gap: 0,
+ children: (0..count)
+ .map(|index| Node::Transcript {
+ key: format!("reader-{index:03}"),
+ resource: wire::Resource {
+ route: serde_json::json!({"reader":index}),
+ ..resource("shared")
+ },
+ })
+ .collect(),
+ },
+ };
+ view.validate().unwrap();
+ instance_mut(&mut app).view = Some(view);
+ app
+}
+fn path(index: usize) -> String {
+ format!("root/reader-{index:03}")
+}
+fn content(index: usize) -> String {
+ format!("Reader content {index:03}")
+}
+
+#[test]
+fn more_than_thirty_two_readers_have_distinct_exact_tokens_and_content() {
+ for count in [5, 32, 33, 64] {
+ let mut app = populated(count);
+ let mounts = app.apps_transcript_mounts();
+ assert_eq!(mounts.len(), count);
+ assert_eq!(
+ mounts
+ .iter()
+ .map(|mount| mount.token)
+ .collect::<BTreeSet<_>>()
+ .len(),
+ count
+ );
+ for (index, mount) in mounts.iter().enumerate() {
+ assert!(!mount.token.is_nil());
+ assert_eq!(mount.resource.route, serde_json::json!({"reader":index}));
+ assert_eq!(mount.owner, instance_mut(&mut app).execution);
+ assert_eq!(
+ &mount.parent,
+ &instance_mut(&mut app).entry.as_ref().unwrap().target
+ );
+ assert_eq!(
+ app.apps.readers.token(&key(), &path(index)),
+ Some(mount.token)
+ );
+ page(&mut app, mount.token, &content(index));
+ assert_eq!(
+ app.apps.readers.mounts[&(key(), path(index))]
+ .source
+ .blocks()[0]
+ .content
+ .text,
+ content(index)
+ );
+ }
+ let screen = draw(&mut app, 140, 512);
+ for index in 0..count {
+ assert!(screen.contains(&content(index)), "reader {index}: {screen}");
+ }
+ assert_eq!(
+ app.apps_transcript_mounts(),
+ mounts,
+ "ordinary reconcile never rebinds a reader"
+ );
+ }
+}
+
+#[test]
+fn many_readers_keep_exact_tokens_when_a_hidden_node_is_replaced() {
+ let count = 33;
+ let mut app = populated(count);
+ let admitted = app.apps_transcript_mounts();
+ assert_eq!(admitted.len(), count);
+ for (index, mount) in admitted.iter().enumerate() {
+ page(&mut app, mount.token, &content(index));
+ }
+ assert_eq!(
+ app.apps.readers.token(&key(), &path(32)),
+ Some(admitted[32].token)
+ );
+ let screen = draw(&mut app, 140, 512);
+ assert!(screen.contains(&content(32)), "{screen}");
+ assert!(!screen.contains(&app.i18n.text("extensions-loading")));
+ assert_eq!(app.apps_transcript_mounts(), admitted);
+
+ let view = instance_mut(&mut app).view.as_mut().unwrap();
+ view.revision = "first-hidden".into();
+ let Node::Column { children, .. } = &mut view.root else {
+ unreachable!()
+ };
+ children.remove(0);
+ children.push(Node::Transcript {
+ key: format!("reader-{count:03}"),
+ resource: wire::Resource {
+ route: serde_json::json!({"reader":count}),
+ ..resource("shared")
+ },
+ });
+ view.validate().unwrap();
+ let replacement = app.apps_transcript_mounts();
+ assert_eq!(replacement.len(), count);
+ assert_eq!(app.apps.readers.token(&key(), &path(0)), None);
+ for (index, previous) in admitted.iter().enumerate().skip(1) {
+ assert_eq!(
+ app.apps.readers.token(&key(), &path(index)),
+ Some(previous.token)
+ );
+ }
+ let fresh = app.apps.readers.token(&key(), &path(count)).unwrap();
+ assert!(admitted.iter().all(|mount| mount.token != fresh));
+ assert_eq!(
+ replacement.last().unwrap().resource.route,
+ serde_json::json!({"reader":count})
+ );
+ assert!(!app.apps_transcript_delivery(transport::Delivery {
+ token: admitted[0].token,
+ output: transport::Output::Event(wire::Event::Invalidated),
+ }));
+ page(&mut app, fresh, &content(count));
+ let screen = draw(&mut app, 140, 512);
+ assert!(screen.contains(&content(count)), "{screen}");
+ assert!(
+ !screen.contains(&content(0)),
+ "the hidden reader cannot remain attached"
+ );
+}
+
+#[test]
+fn an_unmounted_reader_keeps_unavailable_feedback_without_claiming_a_count_limit() {
+ let mut app = populated(1);
+ let screen = draw(&mut app, 140, 40);
+ assert!(
+ screen.contains(&app.i18n.text("transcript-failed")),
+ "{screen}"
+ );
+ let mount = app.apps_transcript_mounts().pop().unwrap();
+ page(&mut app, mount.token, &content(0));
+ let screen = draw(&mut app, 140, 40);
+ assert!(screen.contains(&content(0)), "{screen}");
+ assert!(!screen.contains(&app.i18n.text("transcript-failed")));
+}
diff --git a/crates/tui/src/apps/tree.rs b/crates/tui/src/apps/tree.rs
index afc83ada10..519e702900 100644
--- a/crates/tui/src/apps/tree.rs
+++ b/crates/tui/src/apps/tree.rs
@@ -433,7 +433,7 @@ impl<M> Builder<'_, M> {
} else {
Node::text(
key,
- vec![(self.env.i18n.text("transcript-capacity"), Tone::Subtle)],
+ vec![(self.env.i18n.text("transcript-failed"), Tone::Subtle)],
)
}
}
diff --git a/crates/tui/src/lib.rs b/crates/tui/src/lib.rs
index bfc3e7493e..d333868929 100644
--- a/crates/tui/src/lib.rs
+++ b/crates/tui/src/lib.rs
@@ -291,9 +291,9 @@ where
&& !(app.closing && flushed)
{
if app.closing && state.wait().is_some() {
- state.force();
+ state.force(&mut app);
}
- state.start(&app);
+ state.start(&mut app);
}
if let Some(client) = &client
&& !app.closing
@@ -310,7 +310,7 @@ where
if let Some(request) = app.revision_request() {
if request.needs_checkpoint() {
if let Some(state) = &mut state {
- state.submit_revision(request);
+ state.submit_revision(request, &mut app);
} else {
app.revision_after_checkpoint(
&request,
@@ -329,7 +329,7 @@ where
if let Some(request) = app.recap_request() {
if request.needs_checkpoint() {
if let Some(state) = &mut state {
- state.submit_recap(request);
+ state.submit_recap(request, &mut app);
} else {
app.recap_after_checkpoint(
&request,
@@ -348,7 +348,7 @@ where
if let Some(request) = app.resume_request() {
if request.needs_checkpoint() {
if let Some(state) = &mut state {
- state.submit_resume(request);
+ state.submit_resume(request, &mut app);
} else {
app.resume_after_checkpoint(
&request,
@@ -372,7 +372,7 @@ where
Completed::Branched(request, result)
});
} else if let Some(state) = &mut state {
- state.submit_branch(request);
+ state.submit_branch(request, &mut app);
} else {
app.branch_after_checkpoint(
&request,
@@ -384,7 +384,7 @@ where
if let Some(request) = app.oauth_request() {
if request.needs_checkpoint() {
if let Some(state) = &mut state {
- state.submit_oauth(request);
+ state.submit_oauth(request, &mut app);
} else {
app.oauth_after_checkpoint(
&request,
@@ -532,7 +532,7 @@ where
if let Some(request) = app.plugins_request() {
if request.needs_checkpoint() {
if let Some(state) = &mut state {
- state.submit_plugins(request);
+ state.submit_plugins(request, &mut app);
} else {
app.plugins_after_checkpoint(
&request,
@@ -551,7 +551,7 @@ where
for request in app.apps_requests() {
if request.needs_checkpoint() {
if let Some(state) = &mut state {
- state.submit_app(request);
+ state.submit_app(request, &mut app);
} else {
app.apps_after_checkpoint(
&request,
@@ -791,7 +791,7 @@ where
for request in state.cancel_requests() {
app.abandon_checkpoint(&request);
}
- state.force();
+ state.force(&mut app);
app.closing = true;
dirty = true;
continue;
@@ -872,7 +872,7 @@ where
}
{
if let Some(state) = &mut state {
- state.submit(request);
+ state.submit(request, &mut app);
} else {
let error = app.i18n.text("state-unavailable");
app.after_checkpoint(&request, &Err(error.clone()));
@@ -952,6 +952,10 @@ where
}
let state_wait = state.as_ref().and_then(state::State::wait);
let oauth_wait = app.oauth_wait();
+ // Notifications and completions can change persisted owners even when
+ // they do not schedule a disk write. Only classified local input and
+ // transient reader/paint events retain the derived admission cache.
+ let mut checkpoint_impact = state::Impact::Other;
tokio::select! {
result = async {
match &mut shutdown_job {
@@ -974,7 +978,7 @@ where
Some(wait) => tokio::time::sleep(wait).await,
None => std::future::pending().await,
}
- } => {}
+ } => { checkpoint_impact = state::Impact::Reading; }
request = async {
match oauth_service.as_mut() {
Some(service) => service.recv().await,
@@ -997,6 +1001,15 @@ where
None => std::future::pending().await,
}
} => {
+ // Completing an autosave changes no owner. Keep the sizes from
+ // its capture plus any field deltas typed while it was writing.
+ if written.requests.is_empty() && written.apps.is_empty()
+ && written.oauth.is_none() && written.branch.is_none()
+ && written.recap.is_none() && written.plugins.is_none()
+ && written.resume.is_none() && written.revision.is_none()
+ && written.attachment.is_none() {
+ checkpoint_impact = state::Impact::Reading;
+ }
if let Some(request) = written.plugins
&& app.plugins_after_checkpoint(&request, &written.result)
&& let Some(client) = client.clone() {
@@ -1083,14 +1096,14 @@ where
}
} => {
dirty = app.selection_scroll(std::time::Instant::now());
- if dirty && let Some(state) = &mut state { state.changed(); }
+ if dirty && let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
_ = async {
match &app.notice {
Some(Notice::Clipboard { until, .. }) => tokio::time::sleep(until.saturating_duration_since(std::time::Instant::now())).await,
_ => std::future::pending().await,
}
- } => { app.notice = None; dirty = true; }
+ } => { checkpoint_impact = state::Impact::Reading; app.notice = None; dirty = true; }
_ = async {
let wait = app.chat.history.as_ref()
.and_then(|history| history.wait())
@@ -1108,32 +1121,34 @@ where
Some(wait) => tokio::time::sleep(wait).await,
None => std::future::pending::<()>().await,
}
- } => { dirty = true; }
+ } => { checkpoint_impact = state::Impact::Reading; dirty = true; }
_ = async {
let now=std::time::Instant::now();
let wait=if app.chrome.animating() { Some(Duration::from_millis(16)) }
else { app.chrome.animation.wait(now) };
match wait { Some(wait)=>tokio::time::sleep(wait).await, None=>std::future::pending().await }
} => {
+ checkpoint_impact = state::Impact::Reading;
dirty = true;
}
event = input.next() => {
match event {
Some(Ok(event)) => {
(dirty, effect) = app.input(event);
- if dirty && let Some(state) = &mut state { state.changed(); }
+ checkpoint_impact = app.checkpoint_input_impact();
+ if dirty && let Some(state) = &mut state { state.changed(&mut app, checkpoint_impact); }
}
Some(Err(error)) => return Err(error.into()),
None => break,
}
}
- _ = tokio::time::sleep(Duration::from_millis(100)), if app.attachments.uploading() && app.chrome.window_focused => { dirty = true; }
+ _ = tokio::time::sleep(Duration::from_millis(100)), if app.attachments.uploading() && app.chrome.window_focused => { checkpoint_impact = state::Impact::Reading; dirty = true; }
completed = attachment_jobs.join_next(), if !attachment_jobs.is_empty() => {
match completed {
Some(Ok(pages::attachments::Completed::Browsed(request, result))) => app.attachment_browsed(request, result),
Some(Ok(pages::attachments::Completed::Prepared(ticket, result))) => {
if let Some(ticket) = app.attachment_prepared(ticket, result) {
- if let Some(state) = &mut state { state.submit_attachment(ticket); }
+ if let Some(state) = &mut state { state.submit_attachment(ticket, &mut app); }
else { app.attachment_after_checkpoint(&ticket, &Err("TUI checkpoint unavailable".into())); }
}
}
@@ -1141,14 +1156,14 @@ where
Some(Err(error)) => return Err(error.into()),
None => {}
}
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
dirty = true;
}
completed = theme_jobs.join_next(), if !theme_jobs.is_empty() => {
if let Some(completed) = completed {
let (request, result) = completed?;
app.theme.complete(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
dirty = true;
}
}
@@ -1156,37 +1171,37 @@ where
match completed {
Some(Ok(Completed::Revised(request, result))) => {
app.revision_completed(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::Branched(request, result))) => {
app.branch_completed(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::Oauth(request, result))) => {
if let Some(service) = app.oauth_completed(*request, result) {
oauth_service = Some(service);
}
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::Plugins(request, result))) => {
app.plugins_completed(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::Recap(request,result))) => {
app.recap_completed(request,result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::Resumed(request, result))) => {
app.resume_completed(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::Managed(ticket, result))) => {
app.management_completed(*ticket, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
},
Some(Ok(Completed::Removal(request, result))) => {
app.removal_read(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
},
Some(Ok(Completed::Directory(request, result))) => app.directory_completed(request, result),
Some(Ok(Completed::Extension(request, result))) => app.apps_complete(*request, result),
@@ -1211,7 +1226,7 @@ where
}
Some(Ok(Completed::Reconciled(request, result))) => {
app.reconciled(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::Created(origin, result))) => {
app.creating = false;
@@ -1221,14 +1236,14 @@ where
if app.navigation.current() == origin {
app.apply(Action::Visit(navigation::Route::Session(session.id)));
}
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Err(error) => app.notice = Some(Notice::Diagnostic(error)),
}
}
Some(Ok(Completed::Submitted(request, result))) => {
app.submitted(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::ChatOpened(request, result))) => {
if let Some(id) = app.chat.opened(request, result.map(|opened| *opened)) {
@@ -1241,11 +1256,11 @@ where
Completed::ChatReady(id, result)
});
}
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::ChatPage(request, result))) => {
app.chat.page(request, result);
- if let Some(state) = &mut state { state.changed(); }
+ if let Some(state) = &mut state { state.changed(&mut app, state::Impact::Other); }
}
Some(Ok(Completed::ChatReady(id, Err(error)))) if app.chat.subscription.as_ref() == Some(&id) => app.chat.error = Some(error),
Some(Ok(Completed::Connected(Ok((connected, receiver))))) => {
@@ -1407,6 +1422,7 @@ where
dirty = true;
}
delivery = transcript_deliveries.recv() => {
+ checkpoint_impact = state::Impact::Reading;
if let Some(delivery) = delivery {
dirty |= app.apps_transcript_delivery(delivery);
}
@@ -1425,6 +1441,7 @@ where
&mut terminate
) => break,
}
+ app.checkpoint_changed(checkpoint_impact);
}
app.attachments.disconnect();
app.skills.disconnect();
@@ -1448,7 +1465,7 @@ where
client.disconnect();
}
if !flushed && let Some(state) = &mut state {
- state.finish(&app).await?;
+ state.finish(&mut app).await?;
}
Ok(())
}
diff --git a/crates/tui/src/pages/chat.rs b/crates/tui/src/pages/chat.rs
index 5d0ea26520..11af4d4e41 100644
--- a/crates/tui/src/pages/chat.rs
+++ b/crates/tui/src/pages/chat.rs
@@ -757,6 +757,14 @@ impl Chat {
self.rows = rows;
self.dirty = true;
}
+ pub(crate) fn fixture_cadence(&mut self, rendered: Option<std::time::Instant>) {
+ if let Some(rendered) = rendered {
+ self.cadence.rendered(rendered);
+ self.cadence.arrived();
+ } else {
+ self.cadence.flush();
+ }
+ }
}
#[cfg(test)]
diff --git a/crates/tui/src/state.rs b/crates/tui/src/state.rs
index 75a3f040db..ee957fbe90 100644
--- a/crates/tui/src/state.rs
+++ b/crates/tui/src/state.rs
@@ -26,6 +26,7 @@ use crate::{
};
use maka_client::Error;
use snapshot::Snapshot;
+pub(crate) use snapshot::admission::{Budget, Impact};
use std::{
path::{Path, PathBuf},
sync::{Arc, Mutex},
@@ -119,7 +120,10 @@ impl State {
})
.await?
}
- pub fn changed(&mut self) {
+ /// Keep admission's derived sizes fresh at the same boundary that schedules
+ /// persistence. Field deltas and cursor-only input already account for themselves.
+ pub(crate) fn changed(&mut self, app: &mut App, impact: Impact) {
+ app.checkpoint_changed(impact);
self.deadline
.get_or_insert_with(|| Instant::now() + Duration::from_millis(500));
}
@@ -130,15 +134,16 @@ impl State {
self.deadline
.map(|deadline| deadline.saturating_duration_since(Instant::now()))
}
- pub fn force(&mut self) {
+ pub fn force(&mut self, app: &mut App) {
+ app.checkpoint_changed(Impact::Other);
self.deadline = Some(Instant::now());
}
- pub fn submit(&mut self, request: Submission) {
+ pub fn submit(&mut self, request: Submission, app: &mut App) {
// App permits at most one unresolved request per bounded draft slot.
self.requests
.retain(|pending| pending.session != request.session);
self.requests.push(request);
- self.force();
+ self.force(app);
}
pub fn cancel_requests(&mut self) -> Vec<Submission> {
self.oauth = None;
@@ -158,47 +163,49 @@ impl State {
self.generation += 1;
requests
}
- pub fn submit_oauth(&mut self, request: oauth::Request) {
+ pub fn submit_oauth(&mut self, request: oauth::Request, app: &mut App) {
self.oauth = Some(request);
- self.force();
+ self.force(app);
}
- pub fn submit_plugins(&mut self, request: crate::pages::plugins::Request) {
+ pub fn submit_plugins(&mut self, request: crate::pages::plugins::Request, app: &mut App) {
self.plugins = Some(request);
- self.force();
+ self.force(app);
}
- pub fn submit_recap(&mut self, request: recap::Request) {
+ pub fn submit_recap(&mut self, request: recap::Request, app: &mut App) {
self.recap = Some(request);
- self.force();
+ self.force(app);
}
- pub fn submit_resume(&mut self, request: resume::Request) {
+ pub fn submit_resume(&mut self, request: resume::Request, app: &mut App) {
self.resume = Some(request);
- self.force();
+ self.force(app);
}
- pub fn submit_branch(&mut self, request: branch::Request) {
+ pub fn submit_branch(&mut self, request: branch::Request, app: &mut App) {
self.branch = Some(request);
- self.force();
+ self.force(app);
}
- pub fn submit_attachment(&mut self, request: crate::pages::attachments::Ticket) {
+ pub fn submit_attachment(&mut self, request: crate::pages::attachments::Ticket, app: &mut App) {
self.attachment = Some(request);
- self.force();
+ self.force(app);
}
- pub fn submit_revision(&mut self, request: revision::Request) {
+ pub fn submit_revision(&mut self, request: revision::Request, app: &mut App) {
self.revision = Some(request);
- self.force();
+ self.force(app);
}
- pub fn submit_app(&mut self, request: crate::apps::Request) {
+ pub fn submit_app(&mut self, request: crate::apps::Request, app: &mut App) {
self.apps.push(request);
- self.force();
+ app.checkpoint_changed(Impact::LocalField);
+ self.deadline = Some(Instant::now());
}
pub fn idle(&self) -> bool {
self.job.is_none() && self.deadline.is_none()
}
- pub fn start(&mut self, app: &App) {
+ pub fn start(&mut self, app: &mut App) {
if self.wait() != Some(Duration::ZERO) {
return;
}
self.deadline = None;
- let snapshot = Snapshot::capture(app, &self.root);
+ let mut snapshot = Snapshot::capture(app, &self.root);
+ app.calibrate_checkpoint(&mut snapshot);
let store = self.store.clone();
let requests = std::mem::take(&mut self.requests);
let generation = self.generation;
@@ -280,12 +287,12 @@ impl State {
}
}
/// Terminal EOF/signals have no interactive loop to keep responsive.
- pub async fn finish(&mut self, app: &App) -> Result<(), String> {
+ pub async fn finish(&mut self, app: &mut App) -> Result<(), String> {
self.cancel_requests();
if self.job.is_some() {
self.completed().await;
}
- self.force();
+ self.force(app);
self.start(app);
self.completed().await.result
}
@@ -362,8 +369,8 @@ mod tests {
)
.unwrap();
let (release, blocked) = gate(&state).await;
- state.submit_attachment(ticket.clone());
- state.start(&app);
+ state.submit_attachment(ticket.clone(), &mut app);
+ state.start(&mut app);
assert!(
tokio::time::timeout(Duration::from_millis(30), state.completed())
.await
@@ -458,8 +465,8 @@ mod tests {
app.apps_action(save());
let submission = next(&mut app).unwrap();
let (release, blocked) = gate(&state).await;
- state.submit_app(submission.clone());
- state.start(&app);
+ state.submit_app(submission.clone(), &mut app);
+ state.start(&mut app);
assert!(
tokio::time::timeout(Duration::from_millis(30), state.completed())
.await
@@ -517,9 +524,9 @@ mod tests {
let mut app = crate::apps::tests::app();
app.apps_action(save());
let submission = next(&mut app).unwrap();
- state.submit_app(submission);
+ state.submit_app(submission, &mut app);
let (release, blocked) = gate(&state).await;
- state.start(&app);
+ state.start(&mut app);
state.cancel_requests();
app.apps.disconnect();
release.send(()).unwrap();
@@ -549,8 +556,8 @@ mod tests {
app.apply(Action::Revision(Command::Send));
let request = app.revision_request().unwrap();
let (release, blocked) = gate(&state).await;
- state.submit_revision(request.clone());
- state.start(&app);
+ state.submit_revision(request.clone(), &mut app);
+ state.start(&mut app);
assert!(
tokio::time::timeout(Duration::from_millis(30), state.completed())
.await
@@ -583,9 +590,9 @@ mod tests {
assert!(reopened.revision_request().is_none());
assert!(app.revision_after_checkpoint(&request, &written.result));
assert!(!app.revision_after_checkpoint(&request, &written.result));
- state.submit_revision(request);
+ state.submit_revision(request, &mut app);
let (release, blocked) = gate(&state).await;
- state.start(&app);
+ state.start(&mut app);
state.cancel_requests();
app.revision.disconnect();
release.send(()).unwrap();
@@ -616,8 +623,8 @@ mod tests {
app.apply(Action::Branch(Command::Confirm));
let request = app.branch_request().unwrap();
let (release, blocked) = gate(&state).await;
- state.submit_branch(request.clone());
- state.start(&app);
+ state.submit_branch(request.clone(), &mut app);
+ state.start(&mut app);
assert!(
tokio::time::timeout(Duration::from_millis(20), state.completed())
.await
@@ -625,7 +632,7 @@ mod tests {
);
app.apply(Action::Branch(Command::Close));
app.apply(Action::Visit(Route::Settings));
- state.changed();
+ state.changed(&mut app, Impact::Other);
release.send(()).unwrap();
blocked.await.unwrap();
let written = written(&mut state).await;
@@ -660,9 +667,9 @@ mod tests {
.validate(ROOT)
.is_err()
);
- state.submit_branch(request);
- state.force();
- state.start(&app);
+ state.submit_branch(request, &mut app);
+ state.force(&mut app);
+ state.start(&mut app);
state.cancel_requests();
app.branch.disconnect();
assert!(
@@ -677,8 +684,8 @@ mod tests {
app.input(Event::Paste("original 中文🦀".into()));
let request = app.submission().unwrap();
let (release, blocked) = gate(&state).await;
- state.submit(request.clone());
- state.start(&app);
+ state.submit(request.clone(), &mut app);
+ state.start(&mut app);
assert!(
tokio::time::timeout(Duration::from_millis(20), state.completed())
.await
@@ -686,15 +693,15 @@ mod tests {
);
for _ in 0..100 {
assert!(app.input(Event::Paste("x".into())).0);
- state.changed();
- state.start(&app);
+ state.changed(&mut app, Impact::Other);
+ state.start(&mut app);
}
assert!(state.requests.is_empty());
app.apply(Action::Visit(Route::Session("b".into())));
app.input(Event::Paste("second session".into()));
let second = app.submission().unwrap();
- state.submit(second.clone());
- state.start(&app);
+ state.submit(second.clone(), &mut app);
+ state.start(&mut app);
assert_eq!(
state.requests.len(),
1,
@@ -706,7 +713,7 @@ mod tests {
);
assert!(!state.idle());
app.apply(Action::Visit(Route::Settings));
- state.changed();
+ state.changed(&mut app, Impact::Other);
let mut screen =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)).unwrap();
screen
@@ -720,8 +727,8 @@ mod tests {
assert_eq!(first.requests, vec![request.clone()]);
assert!(app.after_checkpoint(&request, &first.result));
assert_eq!(read(&directory)["drafts"]["a"]["text"], "original 中文🦀");
- state.force();
- state.start(&app);
+ state.force(&mut app);
+ state.start(&mut app);
let latest = written(&mut state).await;
assert!(latest.result.is_ok());
assert_eq!(latest.requests, vec![second.clone()]);
@@ -747,19 +754,19 @@ mod tests {
app.input(Event::Paste("original".into()));
let request = app.submission().unwrap();
let (release, blocked) = gate(&state).await;
- state.submit(request.clone());
- state.start(&app);
+ state.submit(request.clone(), &mut app);
+ state.start(&mut app);
// Same Root and epoch after reconnect: the exact same submission may be retried.
state.cancel_requests();
app.abandon_pending_submissions();
- state.submit(app.retry_submission().unwrap());
+ state.submit(app.retry_submission().unwrap(), &mut app);
release.send(()).unwrap();
blocked.await.unwrap();
assert!(
written(&mut state).await.requests.is_empty(),
"old acknowledgement cannot dispatch the new attempt"
);
- state.start(&app);
+ state.start(&mut app);
let retried = written(&mut state).await;
assert_eq!(retried.requests, vec![request.clone()]);
assert!(app.after_checkpoint(&request, &retried.result));
@@ -768,8 +775,8 @@ mod tests {
let path = directory.path().join(ROOT).join("default/state.json");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
- state.submit(request.clone());
- state.start(&app);
+ state.submit(request.clone(), &mut app);
+ state.start(&mut app);
let failed = written(&mut state).await;
assert!(failed.result.is_err());
assert!(!app.after_checkpoint(&request, &failed.result));
@@ -790,7 +797,7 @@ mod tests {
"a successful disk write cannot rebind the Host epoch"
);
std::fs::remove_dir(&path).unwrap();
- state.finish(&app).await.unwrap();
+ state.finish(&mut app).await.unwrap();
assert_eq!(read(&directory)["unresolved"][0]["id"], request.id);
assert!(state.idle());
}
@@ -811,8 +818,8 @@ mod tests {
app.apply(Action::Recap(Command::Generate));
let request = app.recap_request().unwrap();
let checkpoint = app.recap.checkpoint().unwrap();
- state.submit_recap(request.clone());
- state.start(&app);
+ state.submit_recap(request.clone(), &mut app);
+ state.start(&mut app);
let written = state.completed().await;
assert!(written.result.is_ok());
assert_eq!(written.recap, Some(request.clone()));
@@ -850,8 +857,8 @@ mod tests {
app.apply(Action::Resume(Command::Start));
let request = app.resume_request().unwrap();
let checkpoint = app.resume.checkpoint().unwrap();
- state.submit_resume(request.clone());
- state.start(&app);
+ state.submit_resume(request.clone(), &mut app);
+ state.start(&mut app);
let written = state.completed().await;
assert!(written.result.is_ok());
assert_eq!(written.resume, Some(request.clone()));
diff --git a/crates/tui/src/state/snapshot.rs b/crates/tui/src/state/snapshot.rs
index 7ec54a0d0a..a21d5061f3 100644
--- a/crates/tui/src/state/snapshot.rs
+++ b/crates/tui/src/state/snapshot.rs
@@ -17,7 +17,7 @@
* under the License.
*/
-mod admission;
+pub(super) mod admission;
use crate::{
app::{Action, App},
@@ -207,9 +207,6 @@ impl Snapshot {
if let Some(oauth) = &self.oauth {
oauth.validate()?;
}
- if self.apps.len() > crate::navigation::tabs::LIMIT {
- return Err("Too many plugin checkpoints".into());
- }
self.plugins.validate(root)?;
let mut addresses = std::collections::BTreeSet::new();
for checkpoint in &self.apps {
@@ -295,6 +292,7 @@ impl Snapshot {
.collect();
app.enter_page();
app.mount_app_views();
+ app.checkpoint_changed(crate::state::Impact::Other);
Ok(())
}
}
@@ -318,6 +316,32 @@ mod tests {
app
}
#[test]
+ fn many_small_plugin_drafts_restore_by_bytes_without_a_tab_count_gate() {
+ let mut original = crate::apps::tests::app();
+ original.apps_action(crate::apps::tests::command(crate::apps::Command::View(
+ crate::apps::Intent::Toggle("enabled".into()),
+ )));
+ let mut encoded = serde_json::to_value(Snapshot::capture(&original, "root")).unwrap();
+ let checkpoint = encoded["apps"][0].clone();
+ encoded["apps"] = serde_json::Value::Array(
+ (0..64)
+ .map(|index| {
+ let mut checkpoint = checkpoint.clone();
+ checkpoint["key"]["route"] = serde_json::json!({"draft": index});
+ checkpoint
+ })
+ .collect(),
+ );
+ let saved: Snapshot = serde_json::from_value(encoded).unwrap();
+ saved.validate("root").unwrap();
+ assert!(super::super::store::encode(&saved).unwrap().len() < 1024 * 1024);
+ let mut reopened = app();
+ saved.restore(&mut reopened, false).unwrap();
+ let restored = Snapshot::capture(&reopened, "root");
+ assert_eq!(restored.apps.len(), 64);
+ restored.validate("root").unwrap();
+ }
+ #[test]
fn checkpoint_restores_drafts_preferences_and_original_unknown_identity_without_dispatching() {
let mut original = app();
original.apply(Action::Visit(Route::Session("a".into())));
diff --git a/crates/tui/src/state/snapshot/admission.rs b/crates/tui/src/state/snapshot/admission.rs
index 63c155e8ec..b5430688af 100644
--- a/crates/tui/src/state/snapshot/admission.rs
+++ b/crates/tui/src/state/snapshot/admission.rs
@@ -20,8 +20,64 @@
use super::Snapshot;
use crate::{
app::{App, Focus, Notice},
+ apps::{Checkpoint, Key},
navigation::Navigation,
};
+use std::collections::BTreeMap;
+
+/// The current event's effect on the derived checkpoint accounting. Neither
+/// cached sizes nor this transient classification authorize a remote write.
+#[derive(Clone, Copy, Default)]
+pub(crate) enum Impact {
+ /// The owner replacement was checked before committing its field or write.
+ LocalField,
+ /// Only a plugin reader/cursor moved; legal cursor representations are covered.
+ Reading,
+ #[default]
+ Other,
+}
+
+#[derive(Default)]
+pub(crate) struct Budget {
+ current: Option<Charges>,
+ input: Impact,
+}
+
+struct Charges {
+ shell: usize,
+ owners: BTreeMap<Key, usize>,
+ total: usize,
+}
+impl Charges {
+ fn bytes(&self) -> usize {
+ self.shell
+ .saturating_add(self.total)
+ .saturating_add(self.owners.len().saturating_sub(1))
+ }
+ fn replace(&mut self, key: Key, bytes: Option<usize>) {
+ if let Some(previous) = self.owners.remove(&key) {
+ self.total = self.total.saturating_sub(previous);
+ }
+ if let Some(bytes) = bytes {
+ self.total = self.total.saturating_add(bytes);
+ self.owners.insert(key, bytes);
+ }
+ }
+ fn fits(&self, key: &Key, bytes: Option<usize>) -> bool {
+ if !super::super::store::fits(self.shell) || self.total == usize::MAX {
+ return false;
+ }
+ let previous = self.owners.get(key).copied();
+ let count =
+ self.owners.len() - usize::from(previous.is_some()) + usize::from(bytes.is_some());
+ let total = self
+ .shell
+ .saturating_add(self.total.saturating_sub(previous.unwrap_or(0)))
+ .saturating_add(bytes.unwrap_or(0))
+ .saturating_add(count.saturating_sub(1));
+ super::super::store::fits(total)
+ }
+}
#[cfg(test)]
thread_local! { static CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; }
@@ -29,7 +85,6 @@ thread_local! { static CHECKS: std::cell::Cell<usize> = const { std::cell::Cell:
impl Snapshot {
fn candidate(app: &App, navigation: Option<(&Navigation, bool, Option<Focus>)>) -> Self {
let mut snapshot = Self::capture(app, app.checkpoint_root());
- snapshot.apps.clear();
if let Some((navigation, leaving, preserved)) = navigation {
snapshot.navigation = navigation.clone();
if let crate::navigation::Route::Session(id) = &navigation.location().route {
@@ -45,6 +100,29 @@ impl Snapshot {
}
snapshot
}
+
+ fn charges(&mut self, app: &App) -> Charges {
+ let checkpoints = std::mem::take(&mut self.apps);
+ let shell = serde_json::to_vec(self).map_or(usize::MAX, |bytes| bytes.len());
+ let mut charges = Charges {
+ shell,
+ owners: BTreeMap::new(),
+ total: 0,
+ };
+ for checkpoint in &checkpoints {
+ let bytes = checkpoint.capacity_bytes().unwrap_or(usize::MAX);
+ charges.replace(
+ checkpoint.address().clone(),
+ Some(if app.apps.reserves_checkpoint(checkpoint.address()) {
+ bytes.max(crate::apps::CHECKPOINT_MAX_BYTES)
+ } else {
+ bytes
+ }),
+ );
+ }
+ self.apps = checkpoints;
+ charges
+ }
}
impl App {
@@ -52,25 +130,75 @@ impl App {
pub(crate) fn admission_checks() -> usize {
CHECKS.get()
}
- /// Reserve the existing maximum for each retained owner. This is computed
- /// only at admission boundaries; it is not a second stored budget.
+
+ pub(crate) fn checkpoint_changed(&mut self, impact: Impact) {
+ if matches!(impact, Impact::Other) {
+ self.checkpoint_budget.current = None;
+ }
+ }
+ pub(crate) fn checkpoint_input_impact(&self) -> Impact {
+ self.checkpoint_budget.input
+ }
+ pub(crate) fn checkpoint_input(&mut self, impact: Impact) {
+ self.checkpoint_budget.input = impact;
+ }
+ pub(crate) fn calibrate_checkpoint(&mut self, snapshot: &mut Snapshot) {
+ #[cfg(test)]
+ CHECKS.set(CHECKS.get() + 1);
+ self.checkpoint_budget.current = Some(snapshot.charges(self));
+ }
+ fn ensure_checkpoint_budget(&mut self) {
+ if self.checkpoint_budget.current.is_none() {
+ let mut snapshot = Snapshot::capture(self, self.checkpoint_root());
+ self.calibrate_checkpoint(&mut snapshot);
+ }
+ }
+ pub(crate) fn admit_checkpoint(
+ &mut self,
+ key: &Key,
+ checkpoint: Option<&Checkpoint>,
+ reserved: bool,
+ ) -> bool {
+ let bytes = match checkpoint {
+ Some(checkpoint) => {
+ let Some(bytes) = checkpoint.capacity_bytes() else {
+ return false;
+ };
+ Some(if reserved {
+ bytes.max(crate::apps::CHECKPOINT_MAX_BYTES)
+ } else {
+ bytes
+ })
+ }
+ None => None,
+ };
+ self.ensure_checkpoint_budget();
+ let charges = self
+ .checkpoint_budget
+ .current
+ .as_mut()
+ .expect("calibrated budget");
+ if !charges.fits(key, bytes) {
+ return false;
+ }
+ charges.replace(key.clone(), bytes);
+ self.checkpoint_input(Impact::LocalField);
+ true
+ }
+
+ /// Navigation admission uses its actual candidate envelope. Field edits use
+ /// one owner delta; Other changes invalidate it before the next admission.
pub(crate) fn admit_state(
&mut self,
navigation: Option<(&Navigation, bool, Option<Focus>)>,
- extra_kept: usize,
) -> bool {
#[cfg(test)]
CHECKS.set(CHECKS.get() + 1);
- let kept = self.apps.kept_count() + extra_kept;
- let accepted = (|| {
- if kept > crate::navigation::tabs::LIMIT {
- return None;
- }
- let snapshot = Snapshot::candidate(self, navigation);
- let bytes = super::super::store::encode(&snapshot).ok()?.len();
- let reserved = kept * crate::apps::CHECKPOINT_MAX_BYTES + kept.saturating_sub(1);
- Some(super::super::store::fits(bytes.saturating_add(reserved)))
- })() == Some(true);
+ let mut snapshot = Snapshot::candidate(self, navigation);
+ let accepted = super::super::store::fits(snapshot.charges(self).bytes());
+ // A candidate is not committed navigation. Recalibrate from the actual
+ // state at the next admission, including when route preparation fails.
+ self.checkpoint_changed(Impact::Other);
if !accepted {
self.notice = Some(Notice::Local("state-capacity"));
} else if matches!(self.notice, Some(Notice::Local("state-capacity"))) {
@@ -80,8 +208,7 @@ impl App {
}
}
-#[cfg(test)]
-mod tests;
-
#[cfg(test)]
mod pages;
+#[cfg(test)]
+mod tests;
diff --git a/crates/tui/src/state/snapshot/admission/pages.rs b/crates/tui/src/state/snapshot/admission/pages.rs
index 0c48ba5402..e783136407 100644
--- a/crates/tui/src/state/snapshot/admission/pages.rs
+++ b/crates/tui/src/state/snapshot/admission/pages.rs
@@ -32,8 +32,12 @@ fn saved(navigation: Option<Route>) -> crate::navigation::state::State {
.restore()
}
-fn compare(app: &App, expected: Snapshot) {
- let actual = Snapshot::capture(app, app.checkpoint_root());
+fn compare(app: &App, mut expected: Snapshot) {
+ let mut actual = Snapshot::capture(app, app.checkpoint_root());
+ // This compares navigation metadata before/after its commit. An Applied
+ // reply independently replaces the pending owner with its result.
+ expected.apps.clear();
+ actual.apps.clear();
let expected_bytes = super::super::super::store::encode(&expected).unwrap();
let actual_bytes = super::super::super::store::encode(&actual).unwrap();
assert_eq!(
diff --git a/crates/tui/src/state/snapshot/admission/tests.rs b/crates/tui/src/state/snapshot/admission/tests.rs
index bbaf4c3179..8d97668ca2 100644
--- a/crates/tui/src/state/snapshot/admission/tests.rs
+++ b/crates/tui/src/state/snapshot/admission/tests.rs
@@ -25,6 +25,8 @@ use crate::{
use maka_plugins::terminal_ui::{Placement, view::Reply};
use serde_json::json;
+mod native;
+
fn oversized() -> Navigation {
let mut navigation = Navigation::default();
let mut location = Location::from(Route::Settings);
@@ -45,6 +47,34 @@ fn oversized() -> Navigation {
navigation
}
+fn leave_capacity(app: &mut App, headroom: usize) {
+ let current = app.navigation.location().clone();
+ app.navigation = oversized();
+ app.navigation.visit(current);
+ let maximum = super::super::super::store::MAX_BYTES as usize - headroom;
+ let mut snapshot = Snapshot::capture(app, app.checkpoint_root());
+ let mut excess = snapshot.charges(app).bytes().saturating_sub(maximum);
+ let mut navigation = serde_json::to_value(&app.navigation).unwrap();
+ for entry in navigation["entries"].as_array_mut().unwrap() {
+ for key in entry["embedded"].as_array_mut().unwrap() {
+ if let Some(text) = key["route"].as_str().map(str::to_owned) {
+ let remove = excess.div_ceil(2).min(text.len());
+ let replacement = &text[..text.len() - remove];
+ let difference = serde_json::to_vec(&text).unwrap().len()
+ - serde_json::to_vec(replacement).unwrap().len();
+ key["route"] = json!(replacement);
+ excess = excess.saturating_sub(difference);
+ }
+ }
+ }
+ assert_eq!(excess, 0);
+ app.navigation = serde_json::from_value(navigation).unwrap();
+ let mut snapshot = Snapshot::capture(app, app.checkpoint_root());
+ snapshot.validate(app.checkpoint_root()).unwrap();
+ assert!(snapshot.charges(app).bytes() <= maximum);
+ app.checkpoint_changed(Impact::Other);
+}
+
#[test]
fn candidate_navigation_uses_the_store_encoded_limit_without_changing_current_state() {
let mut app = crate::apps::tests::app();
@@ -53,7 +83,7 @@ fn candidate_navigation_uses_the_store_encoded_limit_without_changing_current_st
let mut snapshot = Snapshot::capture(&app, app.checkpoint_root());
snapshot.navigation = candidate.clone();
assert!(super::super::super::store::encode(&snapshot).is_err());
- assert!(!app.admit_state(Some((&candidate, true, None)), 0));
+ assert!(!app.admit_state(Some((&candidate, true, None))));
assert_eq!(serde_json::to_vec(&app.navigation).unwrap(), original);
}
@@ -95,33 +125,110 @@ fn foreground_applied_retains_the_result_when_its_redirect_cannot_be_admitted()
}
#[test]
-fn rejected_growth_does_not_repeat_whole_snapshot_checks_for_local_input_or_polling() {
+fn background_growth_is_recalibrated_before_typing_without_rechecking_cursor_or_polling() {
use crate::apps::{Command, Intent};
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
let mut app = crate::apps::tests::app();
app.apps_action(crate::apps::tests::command(Command::View(Intent::Toggle(
"enabled".into(),
))));
- app.navigation = oversized();
- app.navigation.visit(Route::App(crate::apps::tests::key()));
- assert!(!app.admit_state(None, 0));
+ leave_capacity(&mut app, 1024);
crate::apps::tests::draw(&mut app, 90, 28);
- let before = App::admission_checks();
app.input(Event::Key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)));
+ app.input(Event::Paste("warm".into()));
+ let before = App::admission_checks();
app.input(Event::Key(KeyEvent::new(
KeyCode::Left,
KeyModifiers::SHIFT,
)));
+ assert_eq!(App::admission_checks(), before);
+ let original = serde_json::to_vec(&app.apps.checkpoints("root")).unwrap();
+ // The same Other boundary used by State::changed and background delivery
+ // invalidates a previously warm cache before the very next field event.
+ app.drafts
+ .get_mut("session")
+ .unwrap()
+ .insert(&"x".repeat(2048));
+ app.checkpoint_changed(Impact::Other);
app.input(Event::Paste("local".into()));
for _ in 0..3 {
assert!(app.apps_requests().is_empty());
}
- assert_eq!(App::admission_checks(), before);
- let checkpoint = serde_json::to_value(app.apps.checkpoints("root")).unwrap();
+ assert_eq!(
+ App::admission_checks(),
+ before + 1,
+ "only the invalidated envelope is recalibrated"
+ );
+ assert_eq!(
+ serde_json::to_vec(&app.apps.checkpoints("root")).unwrap(),
+ original
+ );
+ app.input(Event::Paste("still refused".into()));
+ assert_eq!(App::admission_checks(), before + 1);
+ assert_eq!(
+ serde_json::to_vec(&app.apps.checkpoints("root")).unwrap(),
+ original
+ );
+}
+
+#[test]
+fn frozen_writes_share_remaining_bytes_and_unknown_keeps_its_result_reservation() {
+ use crate::apps::{Command, Intent};
+ let (mut app, keys) = native::inspectors(2);
+ leave_capacity(&mut app, crate::apps::CHECKPOINT_MAX_BYTES + 8);
+ // Both ready forms stay visible. Revisiting a clean standalone page would
+ // intentionally queue a Read and make Submit unavailable until it completes.
+ for key in keys {
+ let command = Message::Instance(key, Command::View(Intent::Submit("save".into())));
+ assert!(app.apps_enabled(&command));
+ app.apps_action(command.clone());
+ assert!(
+ !app.apps_enabled(&command),
+ "the actual Submit is now pending"
+ );
+ }
+ let writes = app.apps_requests();
+ assert_eq!(writes.len(), 1, "one result reservation fits; two do not");
+ let write = writes.into_iter().next().unwrap();
+ assert!(write.needs_checkpoint());
+ let mut frozen = Snapshot::capture(&app, app.checkpoint_root());
+ let charges = frozen.charges(&app);
+ assert_eq!(charges.owners.len(), 1);
+ assert_eq!(
+ *charges.owners.values().next().unwrap(),
+ crate::apps::CHECKPOINT_MAX_BYTES
+ );
+ assert!(super::super::super::store::fits(charges.bytes()));
assert!(
- checkpoint[0]["drafts"]["name"]
- .as_str()
- .unwrap()
- .contains("local")
+ app.apps_requests().is_empty(),
+ "refused writes are not retried by polling"
+ );
+ app.apps_complete(
+ write.clone(),
+ Err(crate::apps::io::Failure { unknown: true }),
+ );
+ let mut unknown = Snapshot::capture(&app, app.checkpoint_root());
+ assert_eq!(unknown.charges(&app).bytes(), charges.bytes());
+ let encoded = serde_json::to_value(&unknown).unwrap();
+ assert!(!encoded["apps"][0]["pending"].is_null());
+ // A late known receipt replaces its own frozen identity, even off screen.
+ app.navigation = Navigation::default();
+ app.focus = Focus::Navigation;
+ app.checkpoint_changed(Impact::Other);
+ app.apps_complete(
+ write,
+ Ok(Output::Reply(Reply::Applied {
+ route: json!({"saved": true}),
+ })),
+ );
+ let mut applied = Snapshot::capture(&app, app.checkpoint_root());
+ applied.validate(app.checkpoint_root()).unwrap();
+ assert!(
+ *applied.charges(&app).owners.values().next().unwrap() < crate::apps::CHECKPOINT_MAX_BYTES
+ );
+ let encoded = serde_json::to_value(applied).unwrap();
+ assert_eq!(
+ encoded["apps"][0]["result"]["route"],
+ json!({"saved": true})
);
}
diff --git a/crates/tui/src/state/snapshot/admission/tests/native.rs b/crates/tui/src/state/snapshot/admission/tests/native.rs
new file mode 100644
index 0000000000..d1dfc967c7
--- /dev/null
+++ b/crates/tui/src/state/snapshot/admission/tests/native.rs
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use crate::{app::Action, apps::Key};
+use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
+use maka_protocol::subscription::{decode_observation_frame, decode_session_observation_snapshot};
+use std::time::{Duration, Instant};
+
+pub(super) fn inspectors(count: usize) -> (App, Vec<Key>) {
+ let mut app = crate::apps::tests::app();
+ app.chrome.motion = true;
+ app.chrome.window_focused = true;
+ let mut keys = vec![];
+ for index in 0..count {
+ let mut panel = app.apps.directory[0].clone();
+ panel.method = format!("budget-panel-{index}");
+ panel.descriptor.placement = Placement::Panel;
+ keys.push(Key::of(&panel, Some("session")).unwrap());
+ app.apps.directory.push(panel);
+ }
+ app.apply(Action::Visit(Route::Session("session".into())));
+ app.navigate(crate::navigation::Intent::Inspector(true));
+ let reads = app.apps_requests();
+ assert_eq!(reads.len(), count);
+ for read in reads {
+ assert!(matches!(
+ &read.work,
+ Work::Call {
+ input: maka_plugins::terminal_ui::view::Request::Read { .. },
+ ..
+ }
+ ));
+ app.apps_complete(
+ read,
+ Ok(Output::Reply(Reply::View {
+ view: crate::apps::tests::form(),
+ })),
+ );
+ }
+ assert!(
+ app.apps_requests().is_empty(),
+ "all panels are ready before input"
+ );
+ app.chat.select(&app.navigation.current());
+ app.chat.snapshot = Some(decode_session_observation_snapshot(&json!({
+ "schemaVersion":5,"session":{"sessionId":"session","metadataRevision":1,"status":"active","createdAt":0,"isArchived":false},
+ "projectionRevision":1,"rootTurn":null,"goal":null,
+ "queue":{"hostEpoch":"epoch","queueRevision":0,"steering":[],"followup":[]},"interactions":{"pending":[]}
+ })).unwrap());
+ app.chat.subscription = Some("sub".into());
+ app.chat.fixture_rows(Default::default());
+ draw(&mut app);
+ let path = app
+ .apps
+ .inspector_wells
+ .iter()
+ .find(|well| well.key == keys[0] && well.field == "name")
+ .unwrap()
+ .path
+ .clone();
+ app.apps.inspector.focus(path);
+ app.focus = Focus::Inspector;
+ (app, keys)
+}
+
+fn draw(app: &mut App) {
+ crate::apps::tests::draw(app, 170, 40);
+}
+
+fn field(app: &App, key: &Key) -> serde_json::Value {
+ serde_json::to_value(
+ app.apps
+ .checkpoints(app.checkpoint_root())
+ .into_iter()
+ .find(|checkpoint| checkpoint.address() == key)
+ .unwrap(),
+ )
+ .unwrap()
+}
+
+fn delta(app: &mut App, index: u64, sequence: u64, offset: u64, text: &str, complete: bool) {
+ let mut delta = json!({
+ "kind":"thinking","turnId":"turn","runId":"run",
+ "messageId":format!("live-{index}"),"startOffset":offset,"text":text
+ });
+ if complete {
+ delta["complete"] = json!(true);
+ }
+ app.chat.accept(decode_observation_frame(&json!({
+ "kind":"subscription.session_delta","hostEpoch":"epoch","subscriptionId":"sub","sequence":sequence,"sessionId":"session",
+ "delta":delta
+ })).unwrap()).unwrap();
+}
+
+#[test]
+fn deferred_native_reading_growth_invalidates_field_admission_but_stable_paints_do_not() {
+ for live in [false, true] {
+ let (mut app, keys) = inspectors(1);
+ let key = &keys[0];
+ // Retaining a clean form costs its whole checkpoint, not just the new
+ // characters. Establish this owner before constraining its growth.
+ app.input(Event::Paste("warm".into()));
+ assert_eq!(field(&app, key)["drafts"]["name"], "My noteswarm");
+ leave_capacity(&mut app, 1024);
+ draw(&mut app);
+ assert_eq!(app.focus, Focus::Inspector);
+ app.input(Event::Paste("a".into()));
+ assert_eq!(field(&app, key)["drafts"]["name"], "My noteswarma");
+ let checks = App::admission_checks();
+ for _ in 0..3 {
+ draw(&mut app);
+ app.input(Event::Key(KeyEvent::new(
+ KeyCode::Right,
+ KeyModifiers::NONE,
+ )));
+ }
+ assert_eq!(App::admission_checks(), checks);
+ let reading = app.chat.view.reading_changes();
+ if live {
+ for index in 0..80 {
+ delta(&mut app, index, index + 1, 0, "step", false);
+ }
+ // Hold the real cadence deterministically; no wall-clock sleeps.
+ app.chat
+ .fixture_cadence(Some(Instant::now() + Duration::from_secs(60)));
+ draw(&mut app);
+ assert_eq!(app.chat.view.reading_changes(), reading);
+ } else {
+ app.chat.fixture_rows((1..=80).map(|sequence| (sequence, json!({
+ "type":"user","id":format!("row-{sequence}"),"turnId":"turn","text":"New durable row"
+ }))).collect());
+ }
+ // State::start can capture before the deferred draw: current saved
+ // metadata still fits and its cache is warm, despite newly received data.
+ assert_eq!(field(&app, key)["drafts"]["name"], "My noteswarma");
+ let mut pending = Snapshot::capture(&app, app.checkpoint_root());
+ assert!(super::super::super::super::store::encode(&pending).is_ok());
+ app.calibrate_checkpoint(&mut pending);
+ let checks = App::admission_checks();
+ let original = field(&app, key);
+ if live {
+ app.chat.fixture_cadence(None);
+ }
+ draw(&mut app);
+ assert_ne!(app.chat.view.reading_changes(), reading);
+ assert!(
+ super::super::super::super::store::encode(&Snapshot::capture(
+ &app,
+ app.checkpoint_root()
+ ))
+ .is_err()
+ );
+ app.input(Event::Paste("must be refused".into()));
+ assert_eq!(
+ field(&app, key),
+ original,
+ "text and cursor remain unchanged"
+ );
+ assert_eq!(App::admission_checks(), checks + 1);
+ let reading = app.chat.view.reading_changes();
+ if live {
+ // A body append changes neither the folded identities nor membership.
+ delta(&mut app, 0, 81, 4, " appended", true);
+ }
+ for _ in 0..3 {
+ draw(&mut app);
+ app.input(Event::Paste("still refused".into()));
+ assert_eq!(app.chat.view.reading_changes(), reading);
+ assert_eq!(App::admission_checks(), checks + 1);
+ assert_eq!(field(&app, key), original);
+ }
+ // Once capacity is available, Undo reaches the preceding accepted edit;
+ // no refused event was added to the real Editor journal.
+ let location = app.navigation.location().clone();
+ app.navigation = Navigation::default();
+ app.navigation.visit(location);
+ app.checkpoint_changed(Impact::Other);
+ app.input(Event::Key(KeyEvent::new(
+ KeyCode::Char('z'),
+ KeyModifiers::CONTROL,
+ )));
+ assert_eq!(field(&app, key)["drafts"]["name"], "My noteswarm");
+ }
+}
diff --git a/crates/tui/src/state/store.rs b/crates/tui/src/state/store.rs
index 1f69a3667a..c00ba1fb98 100644
--- a/crates/tui/src/state/store.rs
+++ b/crates/tui/src/state/store.rs
@@ -28,7 +28,7 @@ use std::{
path::{Path, PathBuf},
};
-const MAX_BYTES: u64 = 40 * 1024 * 1024;
+pub(super) const MAX_BYTES: u64 = 40 * 1024 * 1024;
pub(super) fn fits(bytes: usize) -> bool {
bytes as u64 <= MAX_BYTES
diff --git a/crates/tui/src/ui/transcript.rs b/crates/tui/src/ui/transcript.rs
index b45e2691fb..1c628ea0fa 100644
--- a/crates/tui/src/ui/transcript.rs
+++ b/crates/tui/src/ui/transcript.rs
@@ -194,7 +194,7 @@ struct Block {
activity: Option<Activity>,
indent: u16,
}
-#[derive(Clone, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Anchor {
key: MessageKey,
@@ -205,6 +205,9 @@ struct Anchor {
/// Cache by message identity, and retain a logical reading position across reflow.
#[derive(Default)]
pub struct Transcript {
+ /// Deferred source reconciliation and painting can change saved bookmarks
+ /// after the input/notification that requested the frame has completed.
+ reading_changes: u64,
scrollbar: scrollbar::Scrollbar,
timings: HashMap<String, timing::Timing>,
#[cfg(test)]
@@ -248,6 +251,12 @@ pub struct Transcript {
measurement: Option<performance::DrawStats>,
}
impl Transcript {
+ /// Changes to persisted reading metadata made by reconciliation or paint.
+ /// Direct reading input remains the owning surface's ordinary state event.
+ pub(crate) fn reading_changes(&self) -> u64 {
+ self.reading_changes
+ }
+
/// Call before reconciliation and drawing, using the shell's motion policy.
pub fn motion(&mut self, now: Option<std::time::Instant>) {
self.motion = now;
@@ -440,6 +449,9 @@ impl Transcript {
) {
match self.blocks.get_mut(&key) {
Some(block) if block.revision != revision || block.kind != kind => {
+ if block.kind.foldable() != kind.foldable() {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ }
let live = self.live_update
|| matches!(revision, Revision::Live(_))
|| matches!(block.revision, Revision::Live(_));
@@ -472,6 +484,13 @@ impl Transcript {
block.kind = kind;
}
None => {
+ let restored = self
+ .restore_folds
+ .as_ref()
+ .is_some_and(|folds| folds.contains_key(&key));
+ if kind.foldable() != restored {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ }
let Content {
text,
changes,
@@ -552,7 +571,15 @@ impl Transcript {
self.source_order = std::mem::take(&mut self.order);
self.reconcile_groups(i18n);
let retained: HashSet<_> = self.source_order.iter().chain(self.groups.keys()).collect();
- self.blocks.retain(|key, _| retained.contains(key));
+ let mut removed_fold = false;
+ self.blocks.retain(|key, block| {
+ let keep = retained.contains(key);
+ removed_fold |= !keep && block.kind.foldable();
+ keep
+ });
+ if removed_fold {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ }
if let Some(folds) = &mut self.restore_folds {
folds.retain(|key, folded| {
if let Some(block) = self.blocks.get_mut(key) {
@@ -571,11 +598,15 @@ impl Transcript {
self.refresh_search(false);
if self.relocate {
self.relocate = false;
- self.anchor = self.order.first().cloned().map(|key| Anchor {
+ let anchor = self.order.first().cloned().map(|key| Anchor {
key,
source: 0,
screen_row: 0,
});
+ if self.anchor != anchor {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ self.anchor = anchor;
+ }
self.top = 0;
}
}
@@ -814,7 +845,11 @@ impl Transcript {
.min(bottom);
if top != self.top {
self.top = top;
- self.anchor = self.position(top);
+ let anchor = self.position(top);
+ if self.anchor != anchor {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ self.anchor = anchor;
+ }
}
}
self.selection_geometry(area);
diff --git a/crates/tui/src/ui/transcript/groups.rs b/crates/tui/src/ui/transcript/groups.rs
index 6fe82a3197..e5cab251f7 100644
--- a/crates/tui/src/ui/transcript/groups.rs
+++ b/crates/tui/src/ui/transcript/groups.rs
@@ -96,6 +96,9 @@ impl Transcript {
}
start = end;
}
+ if self.groups != old_groups {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ }
// If a group dissolves, keep reading its surviving real tool, not an
// unrelated message that happens to occupy the old screen coordinate.
if let Some(anchor) = &mut self.anchor
@@ -222,7 +225,11 @@ impl Transcript {
}
self.order.push(key.clone());
}
- self.selected = self.selected.as_ref().and_then(|key| self.visible_key(key));
+ let selected = self.selected.as_ref().and_then(|key| self.visible_key(key));
+ if self.selected != selected {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ self.selected = selected;
+ }
if let Some(anchor) = &mut self.anchor
&& !self.order.contains(&anchor.key)
{
@@ -232,10 +239,12 @@ impl Transcript {
.get(&anchor.key)
.and_then(|members| members.first())
{
+ self.reading_changes = self.reading_changes.wrapping_add(1);
anchor.key = member.clone();
anchor.source = 0;
}
} else if let Some(group) = self.membership.get(&anchor.key) {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
anchor.key = group.clone();
anchor.source = 0;
}
diff --git a/crates/tui/src/ui/transcript/search.rs b/crates/tui/src/ui/transcript/search.rs
index f17e92961d..2bbef7665c 100644
--- a/crates/tui/src/ui/transcript/search.rs
+++ b/crates/tui/src/ui/transcript/search.rs
@@ -243,7 +243,11 @@ impl Transcript {
.as_ref()
.is_some_and(|active| search.matches.contains(active))
{
- search.active = search.matches.first().cloned();
+ let active = search.matches.first().cloned();
+ if search.active != active {
+ self.reading_changes = self.reading_changes.wrapping_add(1);
+ search.active = active;
+ }
}
// Appends/prepends update the count, but never move the user's viewport.
if reveal {
diff --git a/crates/tui/src/view/session.rs b/crates/tui/src/view/session.rs
index d50154eac5..bbcbaa2a5f 100644
--- a/crates/tui/src/view/session.rs
+++ b/crates/tui/src/view/session.rs
@@ -109,8 +109,12 @@ pub(super) fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect, id: &str) {
.saturating_sub(search_height + u16::from(parts[0].height > 4)),
);
if !search::body(frame, app, body) {
+ let reading = app.chat.view.reading_changes();
app.hits
.extend(app.chat.draw(frame, body, &app.i18n, app.chrome.ascii));
+ if app.chat.view.reading_changes() != reading {
+ app.checkpoint_changed(crate::state::Impact::Other);
+ }
}
search::draw(
frame,
diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md
index bd1acec93d..a6f1fe839f 100644
--- a/packages/plugin-sdk/README.md
+++ b/packages/plugin-sdk/README.md
@@ -158,7 +158,7 @@ Host plugins use `ctx.tui.app(name, { entry, backend, resources? }, descriptor,
The UI entry exports a default factory `({ tui }) => ({ read, submit, recover? })`, initialized once per stable document in its own VM. It receives only pure node and field builders; source creation, storage, services and jobs stay in the original business activation. `read(route, cx)` returns a View v7 body built with `tui` (columns, rows, splits, tabs, text, Markdown, controls and fields). The SDK adds the version. Stable sibling keys preserve focus and editing state; `cx.t(en, zhCN, z [...]
-The Host admits up to four concurrent page VMs, each with a 128 MiB JavaScript heap limit and a 200 ms synchronous execution slice. These are execution budgets, not total process memory limits or a hostile-code sandbox. Hidden drafts do not reserve VMs; accepted writes retain their owner until settlement. A failed page stops observation and preserves its last valid view and loaded transcript for local reading. Rebinding is explicit and never replays an uncertain write. Page failure does [...]
+The Host creates page VMs on demand, without a page-count quota. Each has a 128 MiB JavaScript heap limit and a 200 ms synchronous execution slice. These are execution budgets, not total process memory limits or a hostile-code sandbox. Hidden drafts do not reserve VMs; accepted writes retain their owner until settlement. A failed page stops observation and preserves its last valid view and loaded transcript for local reading. Rebinding is explicit and never replays an uncertain write. Pa [...]
`tui.boundary(key, body, { bottom?, padding?, emphasis?, activity? })` frames any body, including ordinary inputs. The optional bottom contains text, buttons or nested rows of those nodes; it is clipped to one right-aligned border row without taking body space. Body and bottom keys must differ. Padding has `horizontal` and `vertical` cells, each 0–4. Defaults are no bottom, zero padding, `emphasis: 'normal'` and `activity: 'idle'`. A visible `'accent'` / `'busy'` border uses the kernel's [...]
@@ -185,7 +185,7 @@ log.append(key, 'Finished\n', '1');
`replace`, `append`, `remove` and `timing` publish contiguous resource updates without rereading the View. Record keys and revisions are stable presentation identities; they grant no native Session, file or mutation authority. Surrounding actions still use the usual authorization, CAS and recovery contract. `Ctrl+F` finds within the loaded page; End or the new-content marker follows the tail. Selecting text pauses following.
-The helper owns snapshots, cursors and cancellation per caller, document and reader mount. Open and Read both require the same mount UUID; multiple nodes can independently read the same source within one document. The source permits four concurrent mounts. Removing a reader closes its stream; retiring a page closes its document and readers. It retains at most 4,096 records / 32 MiB of source; pages retain up to 256 records / 4 MiB, with one larger record allowed up to 16 MiB. Large recor [...]
+The helper owns snapshots, cursors and cancellation per caller, document and reader mount. Open and Read both require the same mount UUID; multiple nodes can independently read the same source within one document. Removing a reader closes its stream; retiring a page closes its document and readers. It retains at most 4,096 records / 32 MiB of source; pages retain up to 256 records / 4 MiB, with one larger record allowed up to 16 MiB. Large records use ordered UTF-8 JSON fragments within [...]
The [Board example](../../crates/cli/tests/fixtures/board-plugin/host.mjs) includes three columns, nested card editing, storage CAS and live refresh. Its [PTY test](../../crates/cli/tests/integration/tui/board.rs) installs it while the TUI is running, interacts with it and checks the persisted domain data.
diff --git a/packages/plugin-sdk/README.zh-CN.md b/packages/plugin-sdk/README.zh-CN.md
index 45decad44d..e790064e29 100644
--- a/packages/plugin-sdk/README.zh-CN.md
+++ b/packages/plugin-sdk/README.zh-CN.md
@@ -162,7 +162,7 @@ Host 插件通过 `ctx.tui.app(name, { entry, backend, resources? }, descriptor,
UI entry 默认导出 `({ tui }) => ({ read, submit, recover? })` factory,每个稳定 document 在独立 VM 中仅初始化一次。factory 只收到纯节点与字段 builders;数据源创建、storage、services 与 jobs 留在原业务激活中。`read(route, cx)` 返回用 `tui` 构造的 View v7 内容,包括列、行、分栏、标签、文本、Markdown、控件和字段,SDK 自动添加版本。稳定的同级 key 保留焦点与编辑状态;`cx.t(en, zhCN, zhTW)` 选择当前语言。外壳负责布局、本地输入、滚动、确认与草稿恢复;插件使用语义颜色,不输出终端转义序列。
-Host 最多同时准入四个页面 VM,每个 VM 的 JavaScript 堆上限为 128 MiB,同步执行片段上限为 200 ms。这是执行预算,不是进程总内存限制或恶意代码沙箱。隐藏草稿不占 VM;已准入写入保留原执行 owner 直到结算。页面失效后停止观察,保留最后有效视图及已加载的 transcript 供本地阅读;重新绑定需要显式操作,不重放结果未知的写入。页面故障不会重启插件的业务激活或其他页面 VM。
+Host 按需创建页面 VM,不按页面数量设置准入上限。每个 VM 的 JavaScript 堆上限为 128 MiB,同步执行片段上限为 200 ms。这是执行预算,不是进程总内存限制或恶意代码沙箱。隐藏草稿不占 VM;已准入写入保留原执行 owner 直到结算。页面失效后停止观察,保留最后有效视图及已加载的 transcript 供本地阅读;重新绑定需要显式操作,不重放结果未知的写入。页面故障不会重启插件的业务激活或其他页面 VM。
`tui.boundary(key, body, { bottom?, padding?, emphasis?, activity? })` 为任意正文添加边框,正文可使用普通输入字段。可选 bottom 仅包含文本、按钮及其嵌套行,在下边线上右对齐并裁剪为一行,不占正文空间;body 与 bottom 的 key 必须不同。padding 的 `horizontal`、`vertical` 各为 0–4 格。默认无 bottom、零 padding、`emphasis: 'normal'`、`activity: 'idle'`。可见的 `'accent'` / `'busy'` 边框使用内核共享的柔和呼吸,遵循减少动态效果、焦点与浮层设置;终端自有配色保持静态。所有节点仍共享 View 的深度、节点和字节预算,并使用已声明的字段与动作。Rust 对应写法为 `terminal_ui::view::build::boundary(key, body).bottom(node).padding(1, 0).emphasis(Emphasis::Accent).activi [...]
@@ -189,7 +189,7 @@ log.append(key, 'Finished\n', '1');
`replace`、`append`、`remove`、`timing` 发布连续的资源更新,不需重新读取 View。记录 key 与 revision 是稳定的展示身份,不授予原生会话、文件或写入权限;周围的动作仍使用原有授权、CAS 与恢复契约。Ctrl+F 搜索已加载页,End 或新内容标记回到最新位置;选择文本会暂停跟随。
-SDK 按 caller、document 与 reader mount 分别管理快照、游标与取消。Open 和 Read 都必须携带同一个 mount UUID,同一 document 的多个节点可独立读取同一来源;数据源最多允许四个并发 mount。移除 reader 只关闭它的流,页面退休才关闭整个 document 及其 readers。数据源最多保留 4,096 条/32 MiB;一页最多 256 条/4 MiB,单条较大记录可放宽至 16 MiB。大记录用有序 UTF-8 JSON 分片传输,每条消息仍受 Remote 上限约束。更新队列超限会明确使阅读区失效。Rust 插件可通过普通 Remote method/stream 实现同一[公共记录与资源协议](../../crates/plugins/src/terminal_ui/transcript.rs),应用的 `resources` 声明捕获同次激活中的精确来源端点,页面不能调用未声明的同包端点。Slot context 应携带稳定实体身份,节点 key 应区分可独立编辑的实体。
+SDK 按 caller、document 与 reader mount 分别管理快照、游标与取消。Open 和 Read 都必须携带同一个 mount UUID,同一 document 的多个节点可独立读取同一来源。移除 reader 只关闭它的流,页面退休才关闭整个 document 及其 readers。数据源最多保留 4,096 条/32 MiB;一页最多 256 条/4 MiB,单条较大记录可放宽至 16 MiB。大记录用有序 UTF-8 JSON 分片传输,每条消息仍受 Remote 上限约束。广播更新在 reader 之间共享不可变事件及分片。当前记录与去重后的历史快照记录共享 32 MiB 编码保留预算;压力过大时使最旧快照失效,保留当前数据。更新队列超限只使对应 reader 失效。空闲流等待保留精确的资源归属,不占普通执行槽;这些编码预算不代表完整 JavaScript 堆或进程 RSS。Rust 插件可通过普通 Remote method/stream 实现同一[公共记录与资源协议](../../crates/plugins/src/termina [...]
[Board 示例](../../crates/cli/tests/fixtures/board-plugin/host.mjs) 展示三列看板、卡片详情编辑、存储 CAS 与实时刷新。[PTY 测试](../../crates/cli/tests/integration/tui/board.rs) 在 TUI 运行期间安装它、执行交互并读回持久领域数据。
diff --git a/packages/plugin-sdk/src/terminal-transcript.ts b/packages/plugin-sdk/src/terminal-transcript.ts
index 17e719cf4f..8f6d01ef12 100644
--- a/packages/plugin-sdk/src/terminal-transcript.ts
+++ b/packages/plugin-sdk/src/terminal-transcript.ts
@@ -143,7 +143,9 @@ export interface TranscriptStats {
* Each open document mount captures its own immutable snapshot before subscribing.
* Pages contain at most 256 records / 4 MiB, allowing one larger record; encoded
* records are capped at 16 MiB. The source holds at most 4096 blocks / 32 MiB,
- * 4096 timings, and four concurrent mounts. Slow readers get Invalidated on queue overflow.
+ * and 4096 timings. Current records plus distinct historical record/timing versions
+ * share the 32 MiB encoded retention budget; pressure invalidates oldest snapshots.
+ * Reader count is not an admission limit; slow queues are invalidated independently.
* Close the store during plugin cleanup. Local reading never changes the View.
*/
export interface TranscriptStore extends Registration {
diff --git a/packages/plugin-sdk/tests/terminal-capacity.test.mjs b/packages/plugin-sdk/tests/terminal-capacity.test.mjs
new file mode 100644
index 0000000000..4894db6517
--- /dev/null
+++ b/packages/plugin-sdk/tests/terminal-capacity.test.mjs
@@ -0,0 +1,255 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { block, fixture, logicalPage } from './terminal-transcript-harness.mjs';
+
+const token = (i) => `00000000-0000-4000-8000-${String(i + 1).padStart(12, '0')}`;
+const read = (i, fence = 0) => ({
+ resource: 'activity',
+ mount: token(i),
+ fence,
+ direction: 'tail',
+});
+const open = (i) => ({ resource: 'activity', mount: token(i), route: null, locale: 'en' });
+const value = (reply) => {
+ assert.equal(reply.kind, 'value', reply.message);
+ return reply.value;
+};
+
+test('more than 32 same-source readers page independently and preserve exact mount identity', async (t) => {
+ const f = await fixture({ blocks: [block('one')] });
+ t.after(() => f.runtime.dispose());
+ const handles = [];
+ for (let i = 0; i < 40; i++) {
+ handles.push(await f.open('doc', token(i)));
+ assert.deepEqual(await f.next(handles[i]), { kind: 'ready', fence: 0 });
+ assert.equal((await f.page(read(i))).records[0].block.content.text, 'one');
+ assert.equal(f.store.stats.active, i + 1);
+ }
+ const denied = await f.invoke('activity.stream', open(0));
+ assert.equal(denied.code, 'invalid');
+ assert.match(denied.message, /already open/);
+ assert.equal(f.store.stats.opened, 40);
+ await f.runtime.streamClose(handles[4]);
+ assert.equal(f.store.stats.active, 39);
+ assert.equal((await f.invoke('activity.read', read(4))).code, 'revoked');
+ const replacement = await f.open('doc', token(40));
+ assert.deepEqual(await f.next(replacement), { kind: 'ready', fence: 0 });
+ assert.equal((await f.page(read(40))).records[0].block.content.text, 'one');
+ await Promise.all([...handles, replacement].map((handle) => f.runtime.streamClose(handle)));
+ assert.equal(f.store.stats.active, 0);
+ assert.equal(f.store.stats.opened, 41);
+ assert.equal(f.store.stats.closed, 41);
+});
+
+test('page changes, transcript and ordinary streams remain available beyond the old stream limit', async (t) => {
+ let changed;
+ let probes = 0;
+ const f = await fixture({}, async ({ tui, remote }) => {
+ changed = await tui.changes('changed');
+ await remote.stream('probe', () => {
+ probes++;
+ return {
+ next: () => ({ done: true }),
+ cancel() {},
+ close() {
+ probes--;
+ },
+ };
+ });
+ return tui.transcriptResource('activity', { blocks: [block('one')] });
+ });
+ t.after(() => f.runtime.dispose());
+ const readers = [];
+ const changes = [];
+ const extra = [];
+ for (let i = 0; i < 40; i++) {
+ changes.push(value(await f.invoke('changed', null, `page-${i}`)));
+ readers.push(await f.open(`page-${i}`, token(i)));
+ assert.deepEqual(await f.next(readers[i]), { kind: 'ready', fence: 0 });
+ }
+ assert.equal(f.store.stats.active, 40);
+ changed();
+ assert.deepEqual(
+ await Promise.all(changes.map((handle) => f.next(handle))),
+ Array(40).fill(null),
+ );
+ f.store.append(block('one').key, ' live', '2');
+ for (const handle of readers) assert.equal((await f.next(handle)).text, ' live');
+ for (let i = 0; i < 80; i++) extra.push(value(await f.invoke('probe', null)));
+ assert.equal(probes, 80);
+ await f.runtime.streamClose(extra.pop());
+ extra.push(value(await f.invoke('probe', null)));
+ const pending = [...changes, ...readers].map((handle) => f.next(handle));
+ const handles = [...changes, ...readers, ...extra];
+ await Promise.all(handles.map((handle) => f.runtime.streamClose(handle)));
+ assert.deepEqual(await Promise.all(pending), Array(80).fill(null));
+ assert.equal(f.store.stats.active, 0);
+ assert.equal(f.store.stats.closed, 40);
+ assert.equal(probes, 0);
+ for (const handle of handles) await assert.rejects(f.runtime.streamNext(handle), /closed/);
+ const reopened = [];
+ for (let i = 0; i < 160; i++) reopened.push(value(await f.invoke('probe', null)));
+ assert.equal(probes, 160, 'every closed stream released its source');
+ await Promise.all(reopened.map((handle) => f.runtime.streamClose(handle)));
+ assert.equal(probes, 0);
+});
+
+test('a large Replace broadcasts one fragment set while preserving snapshots and cancellation', async (t) => {
+ let decoded = 0;
+ class Decoder extends TextDecoder {
+ decode(...args) {
+ decoded++;
+ return super.decode(...args);
+ }
+ }
+ const f = await fixture({ blocks: [block('one')] }, undefined, Decoder);
+ t.after(() => f.runtime.dispose());
+ const handles = [];
+ for (let i = 0; i < 32; i++) {
+ handles.push(await f.open('doc', token(i)));
+ await f.next(handles[i]);
+ }
+ const large = block('one', '界🚀'.repeat(150000), '2');
+ f.store.replace(large);
+ const fragmentDecodes = decoded;
+ let json = '';
+ let fragments = 0;
+ let retired;
+ for (;;) {
+ const event = await f.next(handles[0]);
+ assert.equal(event.kind, 'replace');
+ assert.equal(event.base, 0);
+ assert.equal(event.revision, 1);
+ assert.equal(event.record.offset, Buffer.byteLength(json));
+ for (let i = 1; i < handles.length; i++) {
+ if (i !== retired) assert.deepEqual(await f.next(handles[i]), event);
+ }
+ json += event.record.json;
+ fragments++;
+ if (retired === undefined) {
+ retired = 7;
+ await f.runtime.streamClose(handles[retired]);
+ assert.equal(f.store.stats.active, 31);
+ assert.equal((await f.invoke('activity.read', read(retired))).code, 'revoked');
+ }
+ if (Buffer.byteLength(json) === event.record.total) break;
+ }
+ assert.ok(fragments > 100);
+ assert.deepEqual(JSON.parse(json), large);
+ assert.equal(fragmentDecodes, fragments, 'decode once per fragment, independent of reader count');
+ for (let i = 0; i < handles.length; i++) {
+ if (i !== retired) assert.equal((await f.page(read(i))).records[0].block.content.text, 'one');
+ }
+ const replacement = await f.open('doc', token(32));
+ assert.deepEqual(await f.next(replacement), { kind: 'ready', fence: 1 });
+ assert.deepEqual((await logicalPage(f, 1, 'tail', null, 'doc', token(32))).records, [large]);
+ await Promise.all([...handles, replacement].map((handle) => f.runtime.streamClose(handle)));
+ assert.equal(f.store.stats.active, 0);
+ assert.equal(f.store.stats.closed, 33);
+});
+
+test('slow-reader overflow leaves a consuming reader and its shared updates live', async (t) => {
+ const f = await fixture({ blocks: [block('one', '')] });
+ t.after(() => f.runtime.dispose());
+ const handles = [];
+ for (let i = 0; i < 40; i++) {
+ handles.push(await f.open('doc', token(i)));
+ await f.next(handles[i]);
+ }
+ for (let revision = 1; revision <= 8193; revision++) {
+ f.store.append(block('one').key, 'x', String(revision + 1));
+ const event = await f.next(handles[0]);
+ assert.equal(event.kind, 'append');
+ assert.equal(event.base, revision - 1);
+ assert.equal(event.revision, revision);
+ }
+ assert.equal(f.store.stats.active, 1);
+ assert.equal(f.store.stats.invalidated, 39);
+ for (const handle of handles.slice(1)) {
+ assert.deepEqual(await f.next(handle), { kind: 'invalidated' });
+ assert.equal(await f.next(handle), null);
+ }
+ f.store.append(block('one').key, ' continuing', '8195');
+ assert.equal((await f.next(handles[0])).text, ' continuing');
+ await Promise.all(handles.map((handle) => f.runtime.streamClose(handle)));
+ assert.equal(f.store.stats.active, 0);
+ assert.equal(f.store.stats.closed, 40);
+});
+
+test('historical versions count once and retire oldest snapshots without losing current data', async (t) => {
+ const text = '界'.repeat(3 * 1024 * 1024);
+ const f = await fixture({
+ blocks: [block('one', text)],
+ timings: [{ turn: 'turn', start_ms: 1 }],
+ });
+ t.after(() => f.runtime.dispose());
+ const handles = [];
+ const reader = async (i, fence) => {
+ const handle = await f.open('doc', token(i));
+ handles.push(handle);
+ assert.deepEqual(await f.next(handle), { kind: 'ready', fence });
+ return handle;
+ };
+ const replace = (revision) => {
+ f.store.replace(block('one', text, String(revision)));
+ f.store.timing({ turn: 'turn', start_ms: revision });
+ };
+ await reader(0, 0);
+ await reader(1, 0);
+ replace(2);
+ await reader(2, 2);
+ replace(3);
+ const fast = await reader(3, 4);
+ assert.equal(f.store.stats.invalidated, 0, 'two readers share the same old version budget');
+ replace(4);
+ assert.equal(f.store.stats.invalidated, 2);
+ assert.equal(f.store.stats.active, 2);
+ for (let i = 0; i < 2; i++) {
+ assert.deepEqual(await f.next(handles[i]), { kind: 'invalidated' });
+ assert.equal((await f.invoke('activity.read', read(i))).code, 'revoked');
+ }
+ const event = await f.next(fast);
+ assert.equal(event.kind, 'replace');
+ assert.equal(event.base, 4);
+ assert.equal(event.revision, 5);
+ assert.equal(event.record.revision, '4');
+ assert.equal((await f.page(read(2, 2))).records[0].revision, '2');
+ await reader(4, 6);
+ const current = await logicalPage(f, 6, 'tail', null, 'doc', token(4));
+ assert.equal(current.records[0].revision, '4');
+ assert.equal(current.records[0].content.text, text);
+ assert.deepEqual(current.timings, [{ turn: 'turn', start_ms: 4 }]);
+ await Promise.all(handles.map((handle) => f.runtime.streamClose(handle)));
+ assert.equal(f.store.stats.active, 0);
+ assert.equal(f.store.stats.closed, 5);
+ await reader(5, 6);
+ replace(5);
+ await reader(6, 8);
+ replace(6);
+ assert.equal(f.store.stats.active, 2);
+ assert.equal(f.store.stats.invalidated, 2, 'released versions no longer consume the budget');
+ await f.store.close();
+ await f.store.close();
+ assert.throws(() => f.store.timing({ turn: 'turn', start_ms: 7 }), { code: 'revoked' });
+ assert.equal(f.store.stats.active, 0);
+ assert.equal(f.store.stats.closed, 7);
+});
diff --git a/packages/plugin-sdk/tests/terminal-transcript-harness.mjs b/packages/plugin-sdk/tests/terminal-transcript-harness.mjs
index e69f8a647b..b28cfd8f1d 100644
--- a/packages/plugin-sdk/tests/terminal-transcript-harness.mjs
+++ b/packages/plugin-sdk/tests/terminal-transcript-harness.mjs
@@ -38,13 +38,13 @@ export const block = (message, text = message, revision = '1') => ({
kind: 'assistant',
content: { text },
});
-export async function fixture(initial = {}, activate) {
+export async function fixture(initial = {}, activate, Decoder = TextDecoder) {
let store;
let tui;
const operations = [];
const runtime = vm.runInNewContext(sdk, {
TextEncoder,
- TextDecoder,
+ TextDecoder: Decoder,
Deno: {
core: {
ops: {
@@ -103,8 +103,15 @@ export async function fixture(initial = {}, activate) {
},
};
}
-export async function logicalPage(f, fence, direction = 'tail', cursor = null, document = 'doc') {
- let page = await f.page({ fence, direction, cursor }, document);
+export async function logicalPage(
+ f,
+ fence,
+ direction = 'tail',
+ cursor = null,
+ document = 'doc',
+ token = mount,
+) {
+ let page = await f.page({ fence, direction, cursor, mount: token }, document);
const records = [];
const timings = [];
let assembly;
@@ -134,7 +141,7 @@ export async function logicalPage(f, fence, direction = 'tail', cursor = null, d
}
timings.push(...page.timings);
if (!page.continuation) break;
- const input = { fence, direction: 'continue', cursor: page.continuation };
+ const input = { fence, direction: 'continue', cursor: page.continuation, mount: token };
page = await f.page(input, document);
assert.deepEqual(await f.page(input, document), page, 'cursor replay is immutable');
}
diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts
index 60414fed25..0b9b47f222 100644
--- a/packages/runtime-host/src/protocol/index.ts
+++ b/packages/runtime-host/src/protocol/index.ts
@@ -121,7 +121,7 @@ export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
// Increment when the same protocol version no longer guarantees safe Client-Host
// interoperability. Mismatches are rejected before domain commands are admitted.
// Native bundle bindings and whole-catalog invalidation require matching clients.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 194 as const;
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 195 as const;
export const RUNTIME_HOST_MAX_MESSAGE_BYTES = 768 * 1024;
export const RUNTIME_HOST_MAX_IN_FLIGHT_DOMAIN_REQUESTS = 64;
export const INTERACTIVE_RUNTIME_HOST_COMPOSITION_ID = 'maka.interactive' as const;
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org