Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pkgs/id/contract/shell-contract.v1.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"contract": "id-shell",
"version": 1,
"revision": 2,
"revision": 3,
"description": "The client-server frame protocol every id shell (terminal, web, native) speaks to a world host. Version 1 is the protocol behind the /id-world/1 ALPN. A shell sends only frames and fields named here; it ignores server frame types and fields it does not know. Additive changes bump `revision`; removing or changing a frame or field needs version 2 and a new ALPN. A new frame kind waits for the journal format work (F11.12, #227).",
"max_frame_bytes": 1048576,
"routing_fields": ["world"],
Expand Down Expand Up @@ -80,6 +80,12 @@
"opens": "query",
"fields": { "capability": "string", "module_hash": "string" }
},
"download_module_admin": {
"class": "admin",
"phases": ["opening"],
"opens": "closed",
"fields": { "admin_token": "string", "module_hash": "string" }
Comment on lines +83 to +87

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Document the new admin module-download interface

This adds an admin-only protocol operation that retrieves non-active modules, but no corresponding design document accompanies the change. A repository-wide Markdown search found only older high-level manifest descriptions, not documentation of this API or its storage and authorization semantics. pkgs/id/AGENTS.md explicitly requires a dated design record for interface/API changes; add that record so the new protocol behavior and rationale are documented.

AGENTS.md reference: pkgs/id/AGENTS.md:L159-L168

Useful? React with 👍 / 👎.

},
"caps": {
"class": "query",
"phases": ["opening", "joined"],
Expand Down
155 changes: 130 additions & 25 deletions pkgs/id/src/commands/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,8 +463,8 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> {
no_relay,
} => {
let manifest = parse_manifest_file(&file)?;
let (endpoint, mut client) = connect(&node, &addrs, no_relay, world.as_deref()).await?;
let state = current_world_state(&mut client, &capability, None).await?;
let (endpoint, client) = connect(&node, &addrs, no_relay, world.as_deref()).await?;
let state = current_world_state(&client, &capability, None).await?;
client.close();
endpoint.close().await;
print!("{}", crate::world_manifest::diff(&manifest, &state));
Expand All @@ -481,8 +481,8 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> {
no_relay,
} => {
let manifest = parse_manifest_file(&file)?;
let (endpoint, mut client) = connect(&node, &addrs, no_relay, world.as_deref()).await?;
let state = current_world_state(&mut client, &capability, Some(&admin_token)).await?;
let (endpoint, client) = connect(&node, &addrs, no_relay, world.as_deref()).await?;
let state = current_world_state(&client, &capability, Some(&admin_token)).await?;
let steps = crate::world_manifest::plan(&manifest, &state);
if steps.is_empty() {
println!("no drift");
Expand All @@ -497,7 +497,7 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> {
);
if !dry_run {
let applied =
apply_steps(&mut client, &admin_token, &capability, &steps).await?;
apply_steps(&client, &admin_token, &capability, &steps).await?;
if applied == steps.len() {
println!("applied {} step(s)", applied);
} else {
Expand Down Expand Up @@ -872,17 +872,34 @@ fn parse_manifest_file(file: &std::path::Path) -> Result<crate::world_manifest::
/// with seed 0 — a seed alone never plans a step, and apply always reads with
/// the admin token.
async fn current_world_state(
client: &mut WorldClient,
client: &WorldClient,
capability: &str,
admin_token: Option<&str>,
) -> Result<crate::world_manifest::WorldState> {
let info = client.info_details(capability).await?;
let caps: crate::world_caps::CapsReport =
serde_json::from_value(client.caps(capability).await?)
.context("host returned a malformed capability report")?;
let profile: crate::world_limits::WorldExecutionProfile =
serde_json::from_value(client.execution_profile(None, Some(capability)).await?)
.context("host returned a malformed execution profile")?;
// One fresh session per read: admin and query frames are served one
// operation per stream, so sequencing these reads on one stream would
// talk to a session the host already finished.
let info = client
.fresh_session()
.await?
.info_details(capability)
.await?;
let caps: crate::world_caps::CapsReport = serde_json::from_value(
client
.fresh_session()
.await?
.caps(capability)
.await?,
)
.context("host returned a malformed capability report")?;
let profile: crate::world_limits::WorldExecutionProfile = serde_json::from_value(
client
.fresh_session()
.await?
.execution_profile(None, Some(capability))
.await?,
)
.context("host returned a malformed execution profile")?;
// The report carries the world's own ceiling as a list; an unrestricted
// ceiling is the whole catalog, which we fold back to "no ceiling".
let ceiling = if caps.ceiling
Expand All @@ -894,7 +911,11 @@ async fn current_world_state(
} else {
Some(caps.ceiling.clone())
};
let (seed, schedules) = client.manifest_state(admin_token, Some(capability)).await?;
let (seed, schedules) = client
.fresh_session()
.await?
.manifest_state(admin_token, Some(capability))
.await?;
Ok(crate::world_manifest::WorldState {
module_hash: info.active_module_hash,
seed: seed.unwrap_or(0),
Expand Down Expand Up @@ -929,19 +950,58 @@ fn step_is_applied(step: &crate::world_manifest::ApplyStep) -> bool {
/// set/cancel — each journaled by the host. Returns how many of the steps
/// were actually applied, so the caller's summary cannot claim credit for
/// any step whose apply path is missing (#818).
///
/// The steps run in an order that makes the plan's result reachable, not
/// strictly in plan order (#807): schedule cancels first, so a manifest
/// that replaces ids at the pending-schedule capacity frees the slots its
/// additions need; the execution profile next, so a module installed in
/// the same apply is instantiated under the manifest's profile, not the
/// previous one (a profile applies on the next install); grants and
/// ceiling next, so a module compiled in the same apply may import the
/// capabilities the manifest grants; then the module install; schedule
/// additions last.
///
/// Each operation runs on a fresh session (see
/// [`WorldClient::fresh_session`]): the host serves admin frames one
/// operation per stream, so a second operation on the same stream would
/// write to a session that no longer has a receiver.
/// Order steps for reachability (see [`apply_steps`]): cancellations
/// first, then profile, grants and ceiling, then the module install,
/// and schedule additions last. The sort is stable, so steps of the
/// same kind keep their plan order.
fn ordered_steps<'a>(
steps: &'a [crate::world_manifest::ApplyStep],
) -> Vec<&'a crate::world_manifest::ApplyStep> {
use crate::world_manifest::ApplyStep;
fn rank(step: &ApplyStep) -> u8 {
match step {
ApplyStep::CancelSchedule { .. } => 0,
ApplyStep::SetProfile { .. } => 1,
ApplyStep::SetGrants { .. } => 2,
ApplyStep::SetCeiling { .. } => 3,
ApplyStep::InstallModule { .. } => 4,
Comment on lines +980 to +982

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reconcile revoked grants after replacing the old program

In a grant-on-use world, if the existing program subscribes to players and the manifest installs a replacement that no longer requests it while setting grants = [], this ordering silently restores the unwanted grant. UpdateCaps removes the grant and reconciles subscriptions, but the actor immediately runs after_change, which evaluates the still-running old program and grants its subscription again (world/actor.rs, apply_subscriptions; world_caps.rs, CapLedger::decide_for). The subsequent installation leaves that grant intact, so apply reports success while the world still differs from the manifest. Grant additions can precede compilation, but removals need to be reconciled after replacing the old program.

Useful? React with 👍 / 👎.

ApplyStep::ScheduleAt { .. } => 5,
}
}
let mut ordered: Vec<&ApplyStep> = steps.iter().collect();
ordered.sort_by_key(|step| rank(step));
ordered
}

async fn apply_steps(
client: &mut WorldClient,
client: &WorldClient,
admin_token: &str,
capability: &str,
steps: &[crate::world_manifest::ApplyStep],
) -> Result<usize> {
use crate::world_manifest::ApplyStep;
let applied = steps.iter().filter(|step| step_is_applied(step)).count();
for step in steps {
let ordered = ordered_steps(steps);
for step in ordered {
match step {
ApplyStep::SetGrants { grants } => {
let current: crate::world_caps::CapsReport =
serde_json::from_value(client.caps(capability).await?)
serde_json::from_value(client.fresh_session().await?.caps(capability).await?)
.context("host returned a malformed capability report")?;
let to_revoke: Vec<String> = current
.granted
Expand All @@ -956,6 +1016,8 @@ async fn apply_steps(
.collect();
if !to_grant.is_empty() || !to_revoke.is_empty() {
client
.fresh_session()
.await?
.update_caps(admin_token, &to_grant, &to_revoke)
.await?;
}
Expand All @@ -967,29 +1029,29 @@ async fn apply_steps(
.into_iter()
.collect::<Vec<_>>()
});
client.set_caps_ceiling(admin_token, &names).await?;
client.fresh_session().await?.set_caps_ceiling(admin_token, &names).await?;
}
ApplyStep::SetProfile { profile } => {
client.set_execution_profile(admin_token, *profile).await?;
client.fresh_session().await?.set_execution_profile(admin_token, *profile).await?;
}
ApplyStep::InstallModule { hash, source, seed } => {
if let Some(source) = source {
let sources = read_compile_sources(source)?;
client.compile(admin_token, sources, *seed, false).await?;
client.fresh_session().await?.compile(admin_token, sources, *seed, false).await?;
} else if let Some(hash) = hash {
// The module is already on the host: fetch its bytes by
// hash and install them under the manifest's seed.
let wasm = client.download_module(capability, hash).await?;
client.install_wasm(admin_token, &wasm, *seed).await?;
let wasm = client.fresh_session().await?.download_module_admin(admin_token, hash).await?;
client.fresh_session().await?.install_wasm(admin_token, &wasm, *seed).await?;
Comment on lines +1044 to +1045

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add CLI integration coverage for the revised apply path

The manifest hash-install path now uses an admin download followed by installation on separate sessions, but the added tests only exercise ordering and direct client operations. There is no test invoking world apply in tests/cli_integration.rs, so the actual command's state-read, planning, routing, and execution sequence remains unverified. pkgs/id/AGENTS.md explicitly requires integration tests there for CLI behavior; add a regression case that applies a manifest naming a previously installed, non-active module through the command.

AGENTS.md reference: pkgs/id/AGENTS.md:L152-L152

Useful? React with 👍 / 👎.

} else {
anyhow::bail!("install_module step names neither a hash nor a source");
}
}
ApplyStep::ScheduleAt { id, at_ms } => {
client.set_schedule(admin_token, id, *at_ms).await?;
client.fresh_session().await?.set_schedule(admin_token, id, *at_ms).await?;
}
ApplyStep::CancelSchedule { id } => {
client.cancel_schedule(admin_token, id).await?;
client.fresh_session().await?.cancel_schedule(admin_token, id).await?;
}
}
}
Expand Down Expand Up @@ -1669,6 +1731,49 @@ mod tests {
assert_eq!(applied, steps.len());
}

/// The execution order is what makes a plan reachable (#807): a
/// cancellation frees the schedule slot an addition needs, and the
/// profile, grants and ceiling all land before the module step that
/// compiles or installs under them.
#[test]
fn apply_steps_run_in_reachability_order() {
use crate::world_manifest::ApplyStep;
let steps = [
ApplyStep::ScheduleAt {
id: "new".to_owned(),
at_ms: 5,
},
ApplyStep::InstallModule {
hash: None,
source: Some(std::path::PathBuf::from("main.roc")),
seed: 0,
},
ApplyStep::SetCeiling { ceiling: None },
ApplyStep::SetGrants { grants: vec![] },
ApplyStep::SetProfile {
profile: crate::world_limits::WorldExecutionProfile::default(),
},
ApplyStep::CancelSchedule {
id: "old".to_owned(),
},
];
let kinds: Vec<&str> = super::ordered_steps(&steps)
.iter()
.map(|step| step.kind())
.collect();
assert_eq!(
kinds,
[
"cancel_schedule",
"set_profile",
"set_grants",
"set_ceiling",
"install_module",
"schedule_at"
]
);
}

/// A manifest `module_source` that names a directory compiles its
/// `main.roc` plus the sibling `.roc` files (and nothing else); a plain
/// file compiles alone, always sent as `main.roc`.
Expand Down Expand Up @@ -1755,7 +1860,7 @@ mod tests {
.join("\n");
assert_eq!(
check_contract(&good).unwrap(),
"3 frames conform to shell contract v1.2"
"3 frames conform to shell contract v1.3"
);
let bad = [
r#"{"from": "client", "frame": {"type": "chat", "text": "too early"}}"#,
Expand Down
6 changes: 3 additions & 3 deletions pkgs/id/src/meta_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ pub fn expect_ok(resp: MetaResponse) -> Result<MetaResponse> {
/// limit instead. Any other read failure passes through unchanged.
pub fn capped_response_error(err: ReadToEndError) -> anyhow::Error {
match err {
ReadToEndError::TooLong => anyhow::anyhow!(
"response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit"
),
ReadToEndError::TooLong => {
anyhow::anyhow!("response too large: exceeds the {MAX_RESPONSE_BYTES}-byte limit")
}
other => other.into(),
}
}
Expand Down
15 changes: 12 additions & 3 deletions pkgs/id/src/world/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1308,15 +1308,24 @@ impl WorldActor {
if self.core.schedules.get(&id) == Some(&at_ms) {
return Ok(self.core.schedules.clone());
}
if self.core.schedules.contains_key(&id) {
// Validate the replacement before anything is persisted:
// a refusal (say, past the horizon) must leave the
// existing schedule standing, in the journal as in
// memory (#807).
let replacing = self.core.schedules.contains_key(&id);
self.core.check_schedule_replacing(
&id,
at_ms,
self.core.clock().now_ms(),
replacing,
)?;
if replacing {
// Journal the cancel before the replacement set:
// replay refuses two pending sets for one id.
self.persist(JournalEntry::ScheduleCancelled { id: id.clone() })?;
self.core.schedules.remove(&id);
self.overdue_at_open.remove(&id);
}
self.core
.check_schedule(&id, at_ms, self.core.clock().now_ms())?;
self.persist(JournalEntry::ScheduleSet {
id: id.clone(),
at_ms,
Expand Down
21 changes: 19 additions & 2 deletions pkgs/id/src/world/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,13 +588,30 @@ impl WorldCore {
/// A malformed id, a duplicate pending id, a full schedule, or a time past
/// the horizon.
pub(crate) fn check_schedule(&self, id: &str, at_ms: u64, now_ms: u64) -> Result<()> {
self.check_schedule_replacing(id, at_ms, now_ms, false)
}

/// Like [`Self::check_schedule`], but for a set that replaces the pending
/// schedule with the same id: the entry being replaced counts as already
/// cancelled, so it is neither a duplicate nor a use of the capacity.
/// Callers validate with this BEFORE persisting the replacement's
/// cancellation, so a refused replacement (say, past the horizon) leaves
/// the existing schedule standing (#807).
pub(crate) fn check_schedule_replacing(
&self,
id: &str,
at_ms: u64,
now_ms: u64,
replacing: bool,
) -> Result<()> {
crate::world_caps::validate_schedule_id(id)?;
ensure!(
!self.schedules.contains_key(id),
replacing || !self.schedules.contains_key(id),
"schedule {id:?} is already pending; cancel it before scheduling it again"
);
let pending = self.schedules.len() - usize::from(replacing);
ensure!(
self.schedules.len() < crate::world_caps::MAX_PENDING_SCHEDULES,
pending < crate::world_caps::MAX_PENDING_SCHEDULES,
"world already has {} pending schedules",
crate::world_caps::MAX_PENDING_SCHEDULES
);
Expand Down
39 changes: 39 additions & 0 deletions pkgs/id/src/world/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3347,6 +3347,45 @@ mod schedule_tests {
assert!(error.to_string().contains("pending schedules"), "{error}");
}

#[test]
fn a_replacement_is_validated_as_a_replacement_not_as_an_addition() {
// #807: the admin set that replaces a pending schedule validates
// against the map as it will be after the replacement - the entry
// being replaced is neither a duplicate nor a use of the capacity -
// so validation can run before the cancellation is persisted, and a
// refusal (here, past the horizon) leaves the original standing.
let now = 1_000_000_000_000u64;
let horizon = crate::world_caps::MAX_SCHEDULE_HORIZON_MS;
let mut core = world(8);
core.schedules.insert("taken".to_owned(), now + 5);
assert!(
core.check_schedule_replacing("taken", now + 9, now, true)
.is_ok(),
"replacing a pending id is not a duplicate"
);
let error = core
.check_schedule_replacing("taken", now + horizon + 1, now, true)
.unwrap_err();
assert!(error.to_string().contains("days past"), "{error}");
assert_eq!(
core.schedules["taken"],
now + 5,
"the refused replacement overwrites nothing"
);

let mut full = world(8);
for index in 0..crate::world_caps::MAX_PENDING_SCHEDULES {
full.schedules.insert(format!("s{index}"), now);
}
assert!(
full.check_schedule_replacing("s0", now + 9, now, true)
.is_ok(),
"a replacement at capacity fits: it frees its own slot"
);
let error = full.check_schedule("one-more", now, now).unwrap_err();
assert!(error.to_string().contains("pending schedules"), "{error}");
}

#[tokio::test]
async fn an_ungranted_schedule_is_refused_and_counted() {
let (mut actor, _clock, token, journal) = scheduling_actor("sched-refused", &[], false);
Expand Down
Loading