Compare commits

..
Author SHA1 Message Date
dckc 6c437ec2f1 feat: abandonAll, explicitly, instead of replacing a session on start
Ending a session breaks every reference and pending answer that lives
only in it, so it takes its own update method rather than happening as
a side effect of start. A second start traps again; the clients take
--abandon-all to end the session a previous run left open.

Generated-by: Claude Code (claude-opus-5-5)
2026-11-18 06:43:15 -06:00
9 changed files with 73 additions and 26 deletions

No files matched your search

+5 -3
View File
@@ -19,6 +19,8 @@ icp canister install counter --mode upgrade -y
node client/counter.mjs http://127.0.0.1:4960 $ID alice.key use c1 incr value node client/counter.mjs http://127.0.0.1:4960 $ID alice.key use c1 incr value
``` ```
A principal has one CapTP session at a time. Here the upgrade ended Alice's; without one, her next run needs `--abandon-all`, which ends her open session and breaks every reference and pending answer that lived only in it.
The output shows each update call and each answer; after the upgrade, Alice's counter picks up where it left off: The output shows each update call and each answer; after the upgrade, Alice's counter picks up where it left off:
``` ```
@@ -48,8 +50,8 @@ With another key file, `use c1` breaks: that home is someone else's. `icp networ
shop() { node client/shop.mjs http://127.0.0.1:4960 $ID "$@"; } shop() { node client/shop.mjs http://127.0.0.1:4960 $ID "$@"; }
shop alice.key mint # moola: 10 into Alice's wallet; issuer on the board shop alice.key mint # moola: 10 into Alice's wallet; issuer on the board
shop bob.key open # widgets: 1 in stock; shop on the board at 3 moola shop bob.key open # widgets: 1 in stock; shop on the board at 3 moola
shop alice.key buy shop alice.key buy --abandon-all
shop alice.key buy # sold out: the payment goes back to the wallet shop alice.key buy --abandon-all # sold out: the payment goes back to the wallet
icp canister install counter --mode upgrade -y icp canister install counter --mode upgrade -y
shop alice.key balances shop alice.key balances
shop bob.key balances shop bob.key balances
@@ -98,7 +100,7 @@ Homes, counters, and the canister's CapTP identity live in a [Loam](https://gith
## Known gaps ## Known gaps
- **The entropy is not secret** from the subnet's nodes, nor from whoever installs; nothing rests on it but the CapTP keys. A real deployment would draw it from `raw_rand` in a first call after install. - **The entropy is not secret** from the subnet's nodes, nor from whoever installs; nothing rests on it but the CapTP keys. A real deployment would draw it from `raw_rand` in a first call after install.
- **One session per principal.** A new `start` from a caller closes the caller's old session. - **One session per principal.** A second `start` traps until the caller's `abandonAll` or an upgrade ends the first.
- **Not offer-safe.** A buyer hands over a payment and trusts the shop's code, which is right here because it's in the same vat; across vats this needs Zoe's escrow. The board is init-only, but anyone may post any name first. - **Not offer-safe.** A buyer hands over a payment and trusts the shop's code, which is right here because it's in the same vat; across vats this needs Zoe's escrow. The board is init-only, but anyone may post any name first.
- **No removal or collection.** A home holds 8 names and can't drop one; spent payments keep their records; Loam garbage collection never runs. - **No removal or collection.** A home holds 8 names and can't drop one; spent payments keep their records; Loam garbage collection never runs.
- **The canister pays for every call** and admits any signed caller; it should refuse strangers before doing work (`canister_inspect_message`). - **The canister pays for every call** and admits any signed caller; it should refuse strangers before doing work (`canister_inspect_message`).
+1 -1
View File
@@ -29,7 +29,7 @@ pub fn build(b: *std.Build) void {
}), }),
}); });
canister.entry = .disabled; canister.entry = .disabled;
canister.root_module.export_symbol_names = &.{ "canister_init", "canister_post_upgrade", "canister_update start", "canister_update deliver" }; canister.root_module.export_symbol_names = &.{ "canister_init", "canister_post_upgrade", "canister_update start", "canister_update deliver", "canister_update abandonAll" };
const canister_step = b.step("canister", "Build the canister to zig-out/bin/counter.wasm"); const canister_step = b.step("canister", "Build the canister to zig-out/bin/counter.wasm");
canister_step.dependOn(&b.addInstallArtifact(canister, .{}).step); canister_step.dependOn(&b.addInstallArtifact(canister, .{}).step);
+9 -1
View File
@@ -12,6 +12,7 @@ const idlFactory = ({ IDL }) => {
return IDL.Service({ return IDL.Service({
start: IDL.Func([Frames], [Frames], []), start: IDL.Func([Frames], [Frames], []),
deliver: IDL.Func([Frames], [Frames], []), deliver: IDL.Func([Frames], [Frames], []),
abandonAll: IDL.Func([], [], []),
}); });
}; };
@@ -34,8 +35,11 @@ const keySeed = async path => {
* @param {string} host the replica, e.g. https://icp-api.io * @param {string} host the replica, e.g. https://icp-api.io
* @param {string} canisterId * @param {string} canisterId
* @param {string} keyFile * @param {string} keyFile
* @param {object} [opts]
* @param {boolean} [opts.abandonAll] first end the principal's open session,
* breaking every reference and pending answer that lives only in it
*/ */
export const connect = async (host, canisterId, keyFile) => { export const connect = async (host, canisterId, keyFile, { abandonAll = false } = {}) => {
const { hostname } = new URL(host); const { hostname } = new URL(host);
const agent = await HttpAgent.create({ const agent = await HttpAgent.create({
host, host,
@@ -44,6 +48,10 @@ export const connect = async (host, canisterId, keyFile) => {
shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost', shouldFetchRootKey: hostname === '127.0.0.1' || hostname === 'localhost',
}); });
const actor = Actor.createActor(idlFactory, { agent, canisterId }); const actor = Actor.createActor(idlFactory, { agent, canisterId });
if (abandonAll) {
await actor.abandonAll();
console.error(' abandoned the previous session');
}
const carry = async (method, frames) => { const carry = async (method, frames) => {
const t0 = performance.now(); const t0 = performance.now();
const reply = await actor[method](frames); const reply = await actor[method](frames);
+8 -5
View File
@@ -2,8 +2,8 @@
/** /**
* @file Call the Counter canister over OCapN. * @file Call the Counter canister over OCapN.
*/ */
const HELP = `usage: counter.mjs HOST CANISTER_ID KEY_FILE init NAME const HELP = `usage: counter.mjs HOST CANISTER_ID KEY_FILE init NAME [--abandon-all]
counter.mjs HOST CANISTER_ID KEY_FILE use NAME [VERB...] counter.mjs HOST CANISTER_ID KEY_FILE use NAME [VERB...] [--abandon-all]
Open a CapTP session to the canister as the principal whose Ed25519 seed is Open a CapTP session to the canister as the principal whose Ed25519 seed is
in KEY_FILE (32 bytes, made if missing), then: in KEY_FILE (32 bytes, made if missing), then:
@@ -14,18 +14,21 @@ in KEY_FILE (32 bytes, made if missing), then:
(incr, decr, value; default: incr value) (incr, decr, value; default: incr value)
Each run's sends are pipelined: one update call after the handshake, plus Each run's sends are pipelined: one update call after the handshake, plus
one for init. HOST is the replica, e.g. http://127.0.0.1:4960, or one for init. A principal has one session at a time; --abandon-all first
ends the one a previous run left open. HOST is the replica, e.g. http://127.0.0.1:4960, or
https://icp-api.io.`; https://icp-api.io.`;
import { connect } from './connect.js'; import { connect } from './connect.js';
const main = async ([host, canisterId, keyFile, command, name, ...verbs]) => { const main = async argv => {
const abandonAll = argv.includes('--abandon-all');
const [host, canisterId, keyFile, command, name, ...verbs] = argv.filter(arg => arg !== '--abandon-all');
if (!name || !['init', 'use'].includes(command)) { if (!name || !['init', 'use'].includes(command)) {
console.error(HELP); console.error(HELP);
process.exitCode = 2; process.exitCode = 2;
return; return;
} }
const peer = await connect(host, canisterId, keyFile); const peer = await connect(host, canisterId, keyFile, { abandonAll });
console.log('session open'); console.log('session open');
const home = peer.fetch('home'); const home = peer.fetch('home');
/** Send each verb without waiting, then print each answer. */ /** Send each verb without waiting, then print each answer. */
+8 -4
View File
@@ -2,7 +2,7 @@
/** /**
* @file Alice buys a widget from Bob, over ERTP in the canister. * @file Alice buys a widget from Bob, over ERTP in the canister.
*/ */
const HELP = `usage: shop.mjs HOST CANISTER_ID KEY_FILE STEP const HELP = `usage: shop.mjs HOST CANISTER_ID KEY_FILE STEP [--abandon-all]
Each STEP runs as the principal whose key is in KEY_FILE (made if missing): Each STEP runs as the principal whose key is in KEY_FILE (made if missing):
@@ -14,7 +14,9 @@ Each STEP runs as the principal whose key is in KEY_FILE (made if missing):
purse at home as "closet" purse at home as "closet"
balances show each purse kept at home balances show each purse kept at home
Run mint and buy as Alice, open as Bob.`; Run mint and buy as Alice, open as Bob. A principal has one session at a
time; --abandon-all first ends the one a previous run left open, breaking
everything that lived only in it.`;
import { connect } from './connect.js'; import { connect } from './connect.js';
@@ -86,13 +88,15 @@ const steps = {
}, },
}; };
const main = async ([host, canisterId, keyFile, step]) => { const main = async argv => {
const abandonAll = argv.includes('--abandon-all');
const [host, canisterId, keyFile, step] = argv.filter(arg => arg !== '--abandon-all');
if (!Object.hasOwn(steps, step ?? '')) { if (!Object.hasOwn(steps, step ?? '')) {
console.error(HELP); console.error(HELP);
process.exitCode = 2; process.exitCode = 2;
return; return;
} }
const peer = await connect(host, canisterId, keyFile); const peer = await connect(host, canisterId, keyFile, { abandonAll });
await steps[step](peer, peer.fetch('home'), peer.fetch('board')); await steps[step](peer, peer.fetch('home'), peer.fetch('board'));
}; };
+3
View File
@@ -5,4 +5,7 @@ service : (entropy : blob) -> {
start : (frames : blob) -> (blob); start : (frames : blob) -> (blob);
// Carry later frames on the caller's session. // Carry later frames on the caller's session.
deliver : (frames : blob) -> (blob); deliver : (frames : blob) -> (blob);
// End the caller's session: every reference held through it and every
// pending answer breaks. What the caller keeps at home stays.
abandonAll : () -> ();
} }
+16 -2
View File
@@ -2,7 +2,9 @@
//! peer. Each caller principal gets one CapTP session: `start` opens it with //! peer. Each caller principal gets one CapTP session: `start` opens it with
//! the caller's `op:start-session`, and `deliver` carries later frames. Each //! the caller's `op:start-session`, and `deliver` carries later frames. Each
//! update call's reply carries whatever frames the canister has for that //! update call's reply carries whatever frames the canister has for that
//! caller. The anonymous principal is refused: it would share one home. //! caller. `abandonAll` ends the caller's session, breaking everything that
//! lives only in it, so that it may start another. The anonymous principal
//! is refused: it would share one home.
//! //!
//! Install with 32 bytes of fresh entropy as the argument (one Candid //! Install with 32 bytes of fresh entropy as the argument (one Candid
//! `blob`). Homes, counters, and the peer's identity then live in stable //! `blob`). Homes, counters, and the peer's identity then live in stable
@@ -125,7 +127,7 @@ fn postUpgrade() !void {
try node.revive(gpa, &stable, sessionRoot(""), try designator()); try node.revive(gpa, &stable, sessionRoot(""), try designator());
} }
const Verb = enum { start, deliver }; const Verb = enum { start, deliver, abandonAll };
/// The anonymous principal's one byte. /// The anonymous principal's one byte.
const anonymous = 0x04; const anonymous = 0x04;
@@ -135,12 +137,20 @@ fn exchange(comptime verb: Verb) !void {
if (std.mem.eql(u8, caller, &.{anonymous})) return error.AnonymousCaller; if (std.mem.eql(u8, caller, &.{anonymous})) return error.AnonymousCaller;
const arg = try copied(ic0.msg_arg_data_size, ic0.msg_arg_data_copy); const arg = try copied(ic0.msg_arg_data_size, ic0.msg_arg_data_copy);
defer gpa.free(arg); defer gpa.free(arg);
if (verb == .abandonAll) {
try node.abandonAll(caller);
const empty = "DIDL\x00\x00";
ic0.msg_reply_data_append(@intFromPtr(empty.ptr), empty.len);
ic0.msg_reply();
return;
}
const frames = try candid.decodeBlob(arg); const frames = try candid.decodeBlob(arg);
var out: std.ArrayList(u8) = .empty; var out: std.ArrayList(u8) = .empty;
defer out.deinit(gpa); defer out.deinit(gpa);
switch (verb) { switch (verb) {
.start => try node.start(caller, frames, &out), .start => try node.start(caller, frames, &out),
.deliver => try node.deliver(caller, frames, &out), .deliver => try node.deliver(caller, frames, &out),
.abandonAll => unreachable,
} }
var reply: std.ArrayList(u8) = .empty; var reply: std.ArrayList(u8) = .empty;
defer reply.deinit(gpa); defer reply.deinit(gpa);
@@ -161,10 +171,14 @@ fn canisterStart() callconv(.c) void {
fn canisterDeliver() callconv(.c) void { fn canisterDeliver() callconv(.c) void {
exchange(.deliver) catch |err| trapWith("deliver", err); exchange(.deliver) catch |err| trapWith("deliver", err);
} }
fn canisterAbandonAll() callconv(.c) void {
exchange(.abandonAll) catch |err| trapWith("abandonAll", err);
}
comptime { comptime {
@export(&canisterInit, .{ .name = "canister_init" }); @export(&canisterInit, .{ .name = "canister_init" });
@export(&canisterPostUpgrade, .{ .name = "canister_post_upgrade" }); @export(&canisterPostUpgrade, .{ .name = "canister_post_upgrade" });
@export(&canisterStart, .{ .name = "canister_update start" }); @export(&canisterStart, .{ .name = "canister_update start" });
@export(&canisterDeliver, .{ .name = "canister_update deliver" }); @export(&canisterDeliver, .{ .name = "canister_update deliver" });
@export(&canisterAbandonAll, .{ .name = "canister_update abandonAll" });
} }
+15 -8
View File
@@ -278,15 +278,11 @@ pub fn Node(comptime Memory: type) type {
self.sessions.deinit(self.gpa); self.sessions.deinit(self.gpa);
} }
/// Open `caller`'s session with its `op:start-session`, closing any /// Open `caller`'s session with its `op:start-session` and append the
/// it had, and append the canister's frames to `reply`. /// canister's frames to `reply`. A caller has one session at a time;
/// see `abandonAll`.
pub fn start(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void { pub fn start(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void {
if (self.sessions.fetchRemove(caller)) |old| { if (self.sessions.contains(caller)) return error.SessionAlreadyStarted;
defer self.gpa.free(old.key);
try self.host.transportClosed(old.value, "replaced by a new start");
try link.settle(&self.host, .flush);
try self.host.releaseSession(old.value);
}
const key = try self.gpa.dupe(u8, caller); const key = try self.gpa.dupe(u8, caller);
errdefer self.gpa.free(key); errdefer self.gpa.free(key);
const session = try self.host.openAcceptedAdvertised(link.transport); const session = try self.host.openAcceptedAdvertised(link.transport);
@@ -294,6 +290,17 @@ pub fn Node(comptime Memory: type) type {
try self.exchange(session, frames, reply); try self.exchange(session, frames, reply);
} }
/// End `caller`'s session, if any, and everything that lives only in
/// it: every reference either side holds through it and every answer
/// still pending, which break. What the caller keeps at home stays.
pub fn abandonAll(self: *Self, caller: []const u8) !void {
const old = self.sessions.fetchRemove(caller) orelse return;
defer self.gpa.free(old.key);
try self.host.transportClosed(old.value, "abandoned by its caller");
try link.settle(&self.host, .flush);
try self.host.releaseSession(old.value);
}
/// Carry later frames on `caller`'s session. /// Carry later frames on `caller`'s session.
pub fn deliver(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void { pub fn deliver(self: *Self, caller: []const u8, frames: []const u8, reply: *std.ArrayList(u8)) !void {
const session = self.sessions.get(caller) orelse return error.NoSessionForCaller; const session = self.sessions.get(caller) orelse return error.NoSessionForCaller;
+8 -2
View File
@@ -181,9 +181,15 @@ test "a caller's home keeps a counter across an upgrade; sessions start over" {
try std.testing.expectEqual(@as(usize, 1), try again.flush(gpa, &node, Settled{ .answers = answers[0..2] })); try std.testing.expectEqual(@as(usize, 1), try again.flush(gpa, &node, Settled{ .answers = answers[0..2] }));
try expectCounts(&.{ 3, 3 }, &answers); try expectCounts(&.{ 3, 3 }, &answers);
// A new start from Alice closes her old session and opens another. // Alice can't start another session while one is open, unless she
// abandons it first.
var refused: Client = undefined;
try refused.open(gpa, 0x63, "alice");
defer refused.host.deinit();
try std.testing.expectError(error.SessionAlreadyStarted, refused.flush(gpa, &node, Opened{}));
try node.abandonAll("alice");
var third: Client = undefined; var third: Client = undefined;
try third.open(gpa, 0x63, "alice"); try third.open(gpa, 0x64, "alice");
defer third.host.deinit(); defer third.host.deinit();
try std.testing.expectEqual(@as(usize, 1), try third.flush(gpa, &node, Opened{})); try std.testing.expectEqual(@as(usize, 1), try third.flush(gpa, &node, Opened{}));
answers = @splat(.{}); answers = @splat(.{});