@sema-agent/core
Version:
Stateless, task-oriented AI agent core
887 lines • 57.5 kB
JavaScript
import { strict as assert } from "node:assert";
import { MAILBOX_CONSUMED_ID_WINDOW, MAILBOX_DUPLICATE_RECORD_ID_CODE, MAILBOX_ROW_MALFORMED_CODE, MAILBOX_INVALID_PEER_META_CODE, MAILBOX_INVALID_DECISION_MOVE_CODE, MAILBOX_INVALID_LEASE_OWNER_CODE, MAILBOX_INVALID_RECORD_ID_CODE, MAILBOX_TOMBSTONED_RECIPIENT_CODE, mailboxRecipientLifecycleOf } from "../mailbox-store.js";
import { beginContract } from "./contract-harness.js";
import { thrownText } from "../thrown-value.js";
import { ANONYMOUS_SCOPE } from "../isolation-scope.js";
import { PRINCIPAL_INBOX_HANDLE } from "../../agents/cross-session-ref.js";
import { mintCrossPrincipalRecord } from "../../agents/org-delivery-gate.js";
export const MAILBOX_CONTRACT_SCOPE = ANONYMOUS_SCOPE;
const msg = (content, sentAt = 1000) => ({ content, sentAt });
async function withStores(mk, fn) {
const live = [];
const make = () => {
const s = mk();
live.push(s);
return s;
};
try {
await fn(make);
}
finally {
for (const s of live.splice(0))
s.close?.();
}
}
export async function mailboxStoreContract(mk, runAssertion, hooks) {
if (hooks !== undefined && hooks.plantRow === undefined && (hooks.unplantable === undefined || hooks.unplantable.trim() === "")) {
throw new TypeError("mailboxStoreContract: pass plantRow, or declare unplantable with the reason this backend keeps no bytes a foreign writer could damage");
}
const { run: runRaw, settle } = beginContract(runAssertion);
const run = (name, fn) => runRaw(name, () => withStores(mk, fn));
const S = MAILBOX_CONTRACT_SCOPE;
run("append 铸单调 seq;claimLease 取全部可见消息(不删);ack 才删;活租约=单消费者", async (make) => {
const s = make();
assert.equal(await s.append(S, "a1", msg("m1")), 1);
assert.equal(await s.append(S, "a1", msg("m2")), 2);
assert.equal(await s.peekCount(S, "a1"), 2);
const lease = await s.claimLease(S, "a1", "w1", 60_000, 10_000);
assert.deepEqual(lease.messages.map((m) => m.content), ["m1", "m2"]);
assert.equal(lease.maxSeq, 2);
assert.equal(await s.claimLease(S, "a1", "w2", 60_000, 20_000), null);
assert.equal(await s.peekCount(S, "a1"), 2);
await s.ack(S, "a1", "w1", 2);
assert.equal(await s.peekCount(S, "a1"), 0);
});
run("X-1 无损:lease 过期/release 后消息按原 seq 回可见;seq 在箱的一生中永不复用", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
const l1 = await s.claimLease(S, "a1", "w1", 1_000, 10_000);
assert.equal(l1.maxSeq, 1);
const l2 = await s.claimLease(S, "a1", "w2", 1_000, 20_000);
assert.deepEqual(l2.messages.map((m) => m.seq), [1]);
await s.releaseLease(S, "a1", "w2");
const l3 = await s.claimLease(S, "a1", "w3", 1_000, 20_500);
assert.deepEqual(l3.messages.map((m) => m.seq), [1]);
await s.ack(S, "a1", "w3", 1);
assert.equal(await s.append(S, "a1", msg("m2")), 2);
});
run("记录身份:箱持有同 id 时 append = 同记录回原 seq 零写 / 异记录点名拒;坏 id 零副作用拒;id 往返;ack 后进已收窗", async (make) => {
const s = make();
const codeOf = async (p) => {
try {
await p;
return undefined;
}
catch (e) {
return e.code;
}
};
const rec = { id: "frame-1", from: "w", content: "m1", sentAt: 1000, hopChain: ["h"], peerMeta: { kind: "peer_message", fromRoot: "root" } };
assert.equal(await s.append(S, "a1", rec), 1);
assert.equal(await s.append(S, "a1", { ...rec, sentAt: 5000 }), 1, "同记录再写(写入时刻不同)= 重放,回原 seq");
assert.equal(await s.peekCount(S, "a1"), 1, "重放零写");
for (const changed of [{ content: "m1'" }, { from: "x" }, { hopChain: [] }, { peerMeta: undefined }]) {
assert.equal(await codeOf(s.append(S, "a1", { ...rec, ...changed })), MAILBOX_DUPLICATE_RECORD_ID_CODE, JSON.stringify(changed));
}
for (const bad of ["", 7, null]) {
const raw = JSON.parse(JSON.stringify({ id: bad, content: "c", sentAt: 1 }));
assert.equal(await codeOf(s.append(S, "a1", raw)), MAILBOX_INVALID_RECORD_ID_CODE, String(bad));
}
assert.equal(await s.peekCount(S, "a1"), 1, "被拒的调用零副作用");
assert.equal(await s.append(S, "a1", msg("plain")), 2, "无 id = 新记录");
assert.equal(await s.append(S, "a2", rec), 1, "同 id 在别的箱 = 别的记录");
const lease = await s.claimLease(S, "a1", "w1", 60_000, 10_000);
assert.deepEqual(lease.messages.map((m) => m.id), ["frame-1", undefined], "id 往返,缺席仍缺席");
await s.ack(S, "a1", "w1", lease.maxSeq);
assert.equal(await s.append(S, "a1", rec), 1, "箱为它收过的记录作答:ack 后同记录在已收窗内,回原 seq");
assert.equal(await s.peekCount(S, "a1"), 0, "窗内重放零写");
});
const K = MAILBOX_CONSUMED_ID_WINDOW;
const rec = (id, content = `body-${id}`) => ({ id, from: "w", content, sentAt: 1_000, hopChain: ["h"], peerMeta: { kind: "peer_message", fromRoot: "root" } });
const consume = async (s, handle, owner) => {
const l = await s.claimLease(S, handle, owner, 60_000, 10_000);
assert.notEqual(l, null);
assert.deepEqual(await s.ack(S, handle, owner, l.maxSeq), { acked: true });
};
const codeAndMessage = async (p) => {
try {
await p;
return {};
}
catch (e) {
return { code: e.code, message: thrownText(e) };
}
};
run("W1 窗内同记录:append(X) → claim → ack → 同面 append(X) ⇒ 首个 seq,零写,再 claim = null", async (make) => {
const s = make();
assert.equal(await s.append(S, "a1", rec("X")), 1);
await consume(s, "a1", "w1");
assert.equal(await s.append(S, "a1", { ...rec("X"), sentAt: 9_000 }), 1, "写入时刻不同仍是同一条(sentAt 不是面)");
assert.equal(await s.peekCount(S, "a1"), 0);
assert.equal(await s.claimLease(S, "a1", "w2", 60_000, 20_000), null);
});
run("W2 窗内异记录:同 id 换内容 ⇒ mailbox.duplicate_record_id,拒句点名 content,零写", async (make) => {
const s = make();
await s.append(S, "a1", rec("X"));
await consume(s, "a1", "w1");
const refused = await codeAndMessage(s.append(S, "a1", rec("X", "another body")));
assert.equal(refused.code, MAILBOX_DUPLICATE_RECORD_ID_CODE);
assert.match(refused.message ?? "", /content/);
assert.equal(await s.peekCount(S, "a1"), 0);
});
run("W3 窗外:X 收后再收 K 条带 id 记录 ⇒ append(X) = 高水位 + 1,箱里一条", async (make) => {
const s = make();
await s.append(S, "a1", rec("X"));
await consume(s, "a1", "w1");
for (let i = 0; i < K; i++)
await s.append(S, "a1", rec(`Y${i}`));
await consume(s, "a1", "w2");
assert.equal(await s.append(S, "a1", rec("X")), K + 2, "出窗的 id 是新记录");
assert.equal(await s.peekCount(S, "a1"), 1);
});
run("W4 窗只算带 id:X 收后再收 K 条无 id 记录 ⇒ append(X) 仍回首个 seq", async (make) => {
const s = make();
await s.append(S, "a1", rec("X"));
await consume(s, "a1", "w1");
for (let i = 0; i < K; i++)
await s.append(S, "a1", msg(`plain-${i}`));
await consume(s, "a1", "w2");
assert.equal(await s.append(S, "a1", rec("X")), 1);
assert.equal(await s.peekCount(S, "a1"), 0);
});
run("W5 寿命:drop 清窗(seq 从 1 重来);reap 留窗,且 reap 清掉的未投记录不进窗", async (make) => {
const s = make();
await s.append(S, "a1", rec("X"));
await consume(s, "a1", "w1");
await s.drop(S, "a1");
assert.equal(await s.append(S, "a1", rec("X")), 1, "drop 结束箱的一生:窗随之清,X 是新记录(seq 1)");
assert.equal(await s.peekCount(S, "a1"), 1);
const r = make();
await r.append(S, "b1", rec("X"));
await consume(r, "b1", "w1");
await r.append(S, "b1", rec("Z"));
assert.equal(await r.reap(S, 100_000, { maxAgeMs: 50_000 }), 1);
assert.equal(await r.append(S, "b1", rec("X")), 1, "reap 留窗:X 仍在窗内");
assert.equal(await r.append(S, "b1", rec("Z")), 3, "reap 清掉的 Z 从没被收过:新记录,高水位之后");
});
run("W8 窗序:第 K + 1 条更新的带 id 记录被收的那一刻最旧那条出窗(分两批 ack)", async (make) => {
const s = make();
await s.append(S, "a1", rec("X"));
await consume(s, "a1", "w1");
for (let i = 0; i < K - 1; i++)
await s.append(S, "a1", rec(`Y${i}`));
await consume(s, "a1", "w2");
assert.equal(await s.append(S, "a1", rec("X")), 1, "窗里恰 K 条,X 是最旧的一条,仍在");
await s.append(S, "a1", rec("Y-last"));
await consume(s, "a1", "w3");
assert.equal(await s.append(S, "a1", rec("Y0")), 2, "次旧的那条仍在窗内");
assert.equal(await s.append(S, "a1", rec("X")), K + 2, "第 K + 1 条进窗,X 出窗:新记录");
});
run("replayOf:append 会不会是重放的只读问 —— 持有集 / 已收窗命中 ⇒ 首个 seq,新记录 ⇒ undefined,异记录 ⇒ 带码拒;问不写、不造箱、不耗 seq,坏消息以 append 的码拒", async (make) => {
const s = make();
const codeOf = async (p) => {
try {
await p;
return undefined;
}
catch (e) {
return e.code;
}
};
const x = rec("X");
assert.equal(await s.replayOf(S, "a1", x), undefined, "空 / 未知的箱:新记录");
assert.equal(await s.peekCount(S, "a1"), 0, "问不写");
assert.equal(await s.append(S, "a1", x), 1, "问过的箱照常铸 seq 1(问没耗 seq)");
assert.equal(await s.replayOf(S, "a1", { ...x, sentAt: 9_000 }), 1, "持有集命中:sentAt 不是面");
assert.equal(await s.replayOf(S, "a2", x), undefined, "同 id 在别的箱 = 别的记录");
assert.equal(await s.replayOf(S, "a1", rec("Z")), undefined, "箱里没有这身份:新记录");
assert.equal(await s.replayOf(S, "a1", msg("no identity")), undefined, "没说身份 = 每次都是新记录");
for (const changed of [{ content: "another" }, { from: "x" }, { hopChain: [] }, { peerMeta: undefined }]) {
assert.equal(await codeOf(s.replayOf(S, "a1", { ...x, ...changed })), MAILBOX_DUPLICATE_RECORD_ID_CODE, JSON.stringify(changed));
}
for (const bad of ["", 7, null]) {
const raw = JSON.parse(JSON.stringify({ id: bad, content: "c", sentAt: 1 }));
assert.equal(await codeOf(s.replayOf(S, "a1", raw)), MAILBOX_INVALID_RECORD_ID_CODE, String(bad));
}
assert.equal(await s.peekCount(S, "a1"), 1, "被拒的问零副作用");
await consume(s, "a1", "w1");
assert.equal(await s.replayOf(S, "a1", x), 1, "ack 之后进已收窗:仍答首个 seq");
assert.equal(await codeOf(s.replayOf(S, "a1", rec("X", "another body"))), MAILBOX_DUPLICATE_RECORD_ID_CODE, "窗内异记录同样带码拒");
assert.equal(await s.peekCount(S, "a1"), 0);
assert.equal(await s.append(S, "a1", x), 1, "append 与 replayOf 同一答案");
assert.equal(await s.append(S, "a1", msg("next")), 2, "问与重放都没耗 seq");
await s.drop(S, "a1");
assert.equal(await s.replayOf(S, "a1", x), undefined, "drop 清窗:问也看不见了");
});
run("replayOf 判箱键与 append 是同一只判官:同一 (scope, handle),两者要么都拒(同码)要么都受;受的键上不存在的箱答 undefined(问不拒、不造箱)", async (make) => {
const verdictOf = async (p) => {
try {
await p;
return "accepted";
}
catch (e) {
const code = e.code;
return `refused:${typeof code === "string" ? code : "uncoded"}`;
}
};
const keys = [
["", "a1"],
[S, ""],
[S, "a\u0000b"],
["a\u0000b", "a1"],
[S, "."],
[S, ".."],
[S, "a/b"],
[S, "a b"],
["../x", "a1"],
[S, "nope"],
];
const x = rec("X");
for (const [scope, handle] of keys) {
const asked = await verdictOf(make().replayOf(scope, handle, x));
const written = await verdictOf(make().append(scope, handle, x));
assert.equal(asked, written, `replayOf 与 append 对 ${JSON.stringify([scope, handle])} 同判`);
if (written === "accepted")
assert.equal(await make().replayOf(scope, handle, x), undefined, `${JSON.stringify([scope, handle])} 是一把键:不存在的箱 ⇒ 新记录`);
}
});
run("lease 窗内 append:后到消息在下次 claim 时可见(lease 只覆盖 claim 时刻快照)", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
const l = await s.claimLease(S, "a1", "w1", 60_000, 10_000);
assert.equal(l.maxSeq, 1);
await s.append(S, "a1", msg("m2"));
await s.ack(S, "a1", "w1", l.maxSeq);
assert.equal(await s.peekCount(S, "a1"), 1);
const next = await s.claimLease(S, "a1", "w2", 60_000, 20_000);
assert.deepEqual(next.messages.map((m) => m.content), ["m2"]);
});
run("drop 清整箱;reap 按最新消息龄整箱老化", async (make) => {
const s = make();
await s.append(S, "a1", msg("old", 1_000));
await s.append(S, "a2", msg("fresh", 90_000));
assert.equal(await s.reap(S, 100_000, { maxAgeMs: 50_000 }), 1);
assert.equal(await s.peekCount(S, "a1"), 0);
assert.equal(await s.peekCount(S, "a2"), 1);
await s.drop(S, "a2");
assert.equal(await s.peekCount(S, "a2"), 0);
});
run("空箱 ⇒ null:没消息就不发租约(既不假装投递,也不 fence 掉后来真正的消费者)", async (make) => {
const s = make();
assert.equal(await s.claimLease(S, "never-written", "o1", 60_000, 1_000), null, "从未写过的箱");
await s.append(S, "a1", msg("m1"));
const first = await s.claimLease(S, "a1", "o1", 60_000, 1_000);
await s.ack(S, "a1", "o1", first.maxSeq);
assert.equal(await s.peekCount(S, "a1"), 0);
assert.equal(await s.claimLease(S, "a1", "o1", 60_000, 2_000), null, "全部 ack 后箱内零可见消息");
assert.equal(await s.claimLease(S, "a2", "ghost", 60_000, 3_000), null);
await s.append(S, "a2", msg("real", 4_000));
const real = await s.claimLease(S, "a2", "o2", 60_000, 4_000);
assert.deepEqual(real?.messages.map((m) => m.content), ["real"], "空取不该留下 fence 后来者的幽灵租约");
});
run("守恒律:一条消息在被 ack 消费之前必须至少投递过一次(maxSeq 不得覆盖未投递项)", async (make) => {
const s = make();
const appended = ["m1", "m2", "m3"];
for (const [i, c] of appended.entries())
await s.append(S, "a1", msg(c, 1_000 + i));
const delivered = new Set();
let round = 0;
while ((await s.peekCount(S, "a1")) > 0) {
round += 1;
assert.ok(round < 10, "要么有限轮内收敛,要么就是投递不动了");
const owner = `w${round}`;
const lease = await s.claimLease(S, "a1", owner, 60_000, 10_000 + round);
assert.notEqual(lease, null, "还有可见消息时 claimLease 不得返回 null");
for (const m of lease.messages)
delivered.add(m.content);
await s.ack(S, "a1", owner, lease.maxSeq);
}
assert.deepEqual([...delivered].sort(), [...appended].sort(), "每条被消费掉的消息都必须先被投递过");
});
run("releaseLease owner-fenced:非持有者的 release 是 no-op(活租约的单消费者窗口不被外人撬开)", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
const held = await s.claimLease(S, "a1", "owner-A", 60_000, 10_000);
assert.equal(held.messages.length, 1);
await s.releaseLease(S, "a1", "not-the-owner");
assert.equal(await s.claimLease(S, "a1", "rival", 60_000, 11_000), null, "A 的活租约必须仍然 fence 住 rival");
await s.releaseLease(S, "a1", "owner-A");
const after = await s.claimLease(S, "a1", "rival", 60_000, 12_000);
assert.deepEqual(after?.messages.map((m) => m.seq), [1], "归还后同一条按原 seq 回可见");
});
run("peerMeta 回环:典型 typed 记录逐字节回读;缺席保持缺席(pre-385/foreign 记录语义);空对象也是「在场」", async (make) => {
const s = make();
const full = {
fromSession: "sess_1",
fromMode: "prompting",
senderKey: "k-1",
kind: "peer_message",
fromScope: "team/a b",
gateReceiptId: "gr-9",
};
await s.append(S, "a1", { content: "typed", sentAt: 1_000, peerMeta: full });
await s.append(S, "a1", { content: "plain", sentAt: 1_001 });
await s.append(S, "a1", { content: "empty-meta", sentAt: 1_002, peerMeta: {} });
const lease = await s.claimLease(S, "a1", "w1", 60_000, 10_000);
assert.deepEqual(lease.messages.map((m) => m.content), ["typed", "plain", "empty-meta"]);
assert.deepEqual(lease.messages[0].peerMeta, full, "六字段逐字节回读");
assert.equal("peerMeta" in lease.messages[1], false, "未带 peerMeta 的记录回读时该键必须缺席(不是 undefined 值)");
assert.deepEqual(lease.messages[2].peerMeta, {}, "空对象=在场但无字段,与缺席区分");
});
run("peerMeta 坏值响亮:garbage 以具名码拒 append,且零副作用(不入箱、不耗 seq、不动租约)", async (make) => {
const s = make();
const seqBefore = await s.append(S, "a1", { content: "anchor", sentAt: 1_000 });
const held = await s.claimLease(S, "a1", "holder", 60_000, 10_000);
assert.equal(held?.messages.length, 1);
const codeOf = (e) => e?.code;
class Meta {
fromSession = "s";
}
const hiddenKey = { fromSession: "s" };
Object.defineProperty(hiddenKey, "bogus", { value: 1, enumerable: false });
for (const [label, bad] of [
["fromMode 集外值", { fromMode: "root" }],
["kind 集外值", { kind: "gossip" }],
["未知键", { fromSession: "s", bogus: 1 }],
["空字符串", { senderKey: "" }],
["非字符串", { gateReceiptId: 7 }],
["数组", ["fromSession"]],
["null", null],
["字符串", "fromSession=x"],
["Date", new Date(0)],
["Map", new Map()],
["class 实例", new Meta()],
["symbol 键", { fromSession: "s", [Symbol("hidden")]: 1 }],
["不可枚举的未知键", hiddenKey],
]) {
let thrown;
try {
await s.append(S, "a1", { content: `bad:${label}`, sentAt: 2_000, peerMeta: bad });
}
catch (e) {
thrown = e;
}
assert.notEqual(thrown, undefined, `${label}:必须拒`);
assert.equal(codeOf(thrown), MAILBOX_INVALID_PEER_META_CODE, `${label}:拒必须带码`);
}
assert.equal(await s.peekCount(S, "a1"), 1, "被拒的 append 不得入箱");
assert.equal(await s.claimLease(S, "a1", "rival", 60_000, 11_000), null, "被拒的 append 不得动活租约");
await s.ack(S, "a1", "holder", held.maxSeq);
assert.equal(await s.append(S, "a1", { content: "next", sentAt: 3_000 }), seqBefore + 1, "被拒的 append 不得消耗 seq");
});
run("peerMeta 不串引用:消费者改写租约批里的 peerMeta,不得改到下次投递的记录", async (make) => {
const s = make();
await s.append(S, "a1", { content: "m1", sentAt: 1_000, peerMeta: { fromMode: "bypass", fromSession: "sess_1" } });
const first = await s.claimLease(S, "a1", "w1", 1_000, 10_000);
first.messages[0].peerMeta.fromSession = "forged";
await s.releaseLease(S, "a1", "w1");
const again = await s.claimLease(S, "a1", "w2", 1_000, 20_000);
assert.deepEqual(again.messages[0].peerMeta, { fromMode: "bypass", fromSession: "sess_1" }, "重投的记录必须是原样");
});
run("hold decision:CAS 一胜一负、负者拿到真值;不受租约围栏;每个租约快照都带它", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
await s.append(S, "a1", msg("m2"));
const held = await s.claimLease(S, "a1", "holder", 60_000, 10_000);
assert.equal(held.messages[0].decision, undefined, "从未 held 的记录没有 decision");
assert.deepEqual(await s.moveDecision(S, "a1", 1, undefined, "held"), { ok: true });
assert.deepEqual(await s.moveDecision(S, "a1", 1, undefined, "held"), { ok: false, current: "held" }, "同一步再走一次:负者拿到当前值");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "held", "denied"), { ok: true }, "不持租约的一方也能落人的决定");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "held", "approved"), { ok: false, current: "denied" }, "后到的答复输给先到的决定");
assert.deepEqual(await s.moveDecision(S, "a1", 2, "held", "approved"), { ok: false, current: "unset" }, "未 held 的记录答 unset");
const snap = await s.claimLease(S, "a1", "holder", 60_000, 11_000);
assert.deepEqual(snap.messages.map((m) => [m.seq, m.decision]), [[1, "denied"], [2, undefined]], "租约快照带每条记录的 decision");
await s.ack(S, "a1", "holder", 1);
assert.deepEqual(await s.moveDecision(S, "a1", 1, "denied", "denied").catch((e) => e.code), MAILBOX_INVALID_DECISION_MOVE_CODE, "终局不再移动(先于存在性判)");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "held", "approved"), { ok: false, current: "gone" }, "ack 掉的记录答 gone");
});
run("decision 律:只向前走,终局不动;坏词 / 坏 seq / 非法边先于任何副作用被拒(带码)", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
const codeOf = async (p) => {
try {
await p;
return undefined;
}
catch (e) {
return e.code;
}
};
for (const [label, seq, expect, next] of [
["unset → approved", 1, undefined, "approved"],
["unset → delivered", 1, undefined, "delivered"],
["held → held", 1, "held", "held"],
["held → dropped", 1, "held", "dropped"],
["delivered → denied", 1, "delivered", "denied"],
["denied → approved", 1, "denied", "approved"],
["unknown word", 1, undefined, "consumed"],
["seq 0", 0, undefined, "held"],
["seq 1.5", 1.5, undefined, "held"],
]) {
assert.equal(await codeOf(s.moveDecision(S, "a1", seq, expect, next)), MAILBOX_INVALID_DECISION_MOVE_CODE, label);
}
for (const bad of [42, null, {}, ["w"]]) {
assert.equal(await codeOf(s.moveDecision(S, "a1", 1, undefined, "held", bad)), MAILBOX_INVALID_DECISION_MOVE_CODE, `holder ${JSON.stringify(bad)}`);
}
const snap = await s.claimLease(S, "a1", "w", 60_000, 10_000);
assert.equal(snap.messages[0].decision, undefined, "被拒的调用零副作用");
for (const [from, to] of [[undefined, "held"], ["held", "approved"], ["approved", "delivered"], ["delivered", "dropped"]]) {
assert.deepEqual(await s.moveDecision(S, "a1", 1, from, to, "w"), { ok: true }, `${String(from)} → ${to}`);
}
});
run("持租者名只有一种拼写:非空白、不超过 256 个字符、无控制字符、无格式字符(零宽 / 方向覆盖) —— claimLease 的 owner 与 moveDecision 的 holder 同读一只判官,先于任何副作用被拒(带各自的码)", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
const codeOf = async (p) => {
try {
await p;
return undefined;
}
catch (e) {
return e.code;
}
};
const BAD = ["", " ", "\t\n", "w\n1", "w\u0007", "w\u0000", "\u0085", 42, null, {}, "n".repeat(257), "w\u200b1", "w\u202e1"];
for (const bad of BAD) {
assert.equal(await codeOf(s.claimLease(S, "a1", bad, 60_000, 10_000)), MAILBOX_INVALID_LEASE_OWNER_CODE, `owner ${JSON.stringify(bad)}`);
assert.equal(await codeOf(s.moveDecision(S, "a1", 1, undefined, "held", bad)), MAILBOX_INVALID_DECISION_MOVE_CODE, `holder ${JSON.stringify(bad)}`);
}
const snap = await s.claimLease(S, "a1", "w", 60_000, 10_000);
assert.ok(snap, "被拒的认领没有占住这个箱");
assert.equal(snap.messages.length, 1);
assert.equal(snap.messages[0].decision, undefined, "被拒的移动零副作用");
assert.ok(await s.claimLease(S, "a1", "w", 60_000, 20_000), "同一持租者重认领");
await s.append(S, "a2", msg("m2"));
assert.ok(await s.claimLease(S, "a2", "worker 7 · 甲", 60_000, 10_000), "带空格 / 标点 / 中文的名字是一个名字");
await s.append(S, "a4", msg("m4"));
assert.ok(await s.claimLease(S, "a4", "n".repeat(256), 60_000, 10_000), "恰好 256 个字符的名字是一个名字");
await s.append(S, "a3", msg("m3"));
assert.ok(await s.claimLease(S, "a3", "A", 60_000, 10_000));
for (const [from, to] of [[undefined, "held"], ["held", "approved"], ["approved", "delivered"]]) {
assert.deepEqual(await s.moveDecision(S, "a3", 1, from, to, "A"), { ok: true }, `A: ${String(from)} → ${to}`);
}
assert.equal(await codeOf(s.moveDecision(S, "a3", 1, "delivered", "dropped", "")), MAILBOX_INVALID_DECISION_MOVE_CODE, "空 holder 是被拒的调用,不是被围栏的调用");
assert.deepEqual(await s.moveDecision(S, "a3", 1, "delivered", "dropped", "A"), { ok: true }, "真持租者照常结清");
});
run("交出之后的出口只归持租者:delivered → dropped 与 ack 同一只租约围栏、与记录状态同一步判;前任持租者的迟到结清被拒", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
assert.ok(await s.claimLease(S, "a1", "A", 1_000, 10_000), "A 持租");
for (const [from, to] of [[undefined, "held"], ["held", "approved"], ["approved", "delivered"]]) {
assert.deepEqual(await s.moveDecision(S, "a1", 1, from, to, "A"), { ok: true }, `A: ${String(from)} → ${to}`);
}
const taken = await s.claimLease(S, "a1", "B", 60_000, 20_000);
assert.deepEqual(taken.messages.map((m) => m.decision), ["delivered"], "B 的快照里记录是 delivered");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "delivered", "dropped", "A"), { ok: false, current: "delivered" }, "前任持租者(A)的结清被拒,记录不动");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "delivered", "dropped"), { ok: false, current: "delivered" }, "不报持租者的一方结清不了");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "delivered", "dropped", "nobody"), { ok: false, current: "delivered" }, "不持租的名字结清不了");
const still = await s.claimLease(S, "a1", "B", 60_000, 21_000);
assert.deepEqual(still.messages.map((m) => m.decision), ["delivered"], "被拒的结清零副作用");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "delivered", "dropped", "B"), { ok: true }, "当前持租者(B)结清");
await s.append(S, "a2", msg("m2"));
assert.ok(await s.claimLease(S, "a2", "C", 1_000, 30_000));
await s.moveDecision(S, "a2", 1, undefined, "held", "C");
await s.moveDecision(S, "a2", 1, "held", "delivered", "C");
await s.append(S, "a3", msg("m3"));
assert.ok(await s.claimLease(S, "a3", "D", 60_000, 30_000));
await s.moveDecision(S, "a3", 1, undefined, "held", "D");
await s.moveDecision(S, "a3", 1, "held", "delivered", "D");
await s.releaseLease(S, "a3", "D");
assert.deepEqual(await s.moveDecision(S, "a3", 1, "delivered", "dropped", "D"), { ok: false, current: "delivered" }, "交还了租约的一方不再持有");
assert.deepEqual(await s.moveDecision(S, "a2", 1, "delivered", "dropped", "C"), { ok: true }, "过期未被接手的租约仍是 C 的");
});
run("人的决定不问租约:另一方持租时,不持租 / 报了别的名字的一方照样落 approve 与 deny", async (make) => {
const s = make();
await s.append(S, "a1", msg("m1"));
await s.append(S, "a1", msg("m2"));
assert.ok(await s.claimLease(S, "a1", "holder", 60_000, 10_000));
await s.moveDecision(S, "a1", 1, undefined, "held", "holder");
await s.moveDecision(S, "a1", 2, undefined, "held", "holder");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "held", "approved"), { ok: true }, "不报持租者的 approve");
assert.deepEqual(await s.moveDecision(S, "a1", 2, "held", "denied", "someone-else"), { ok: true }, "报了别的名字的 deny(名字在这条边上不读)");
assert.deepEqual(await s.moveDecision(S, "a1", 1, "approved", "refused", "someone-else"), { ok: true }, "approved 的终局同样不问租约");
const snap = await s.claimLease(S, "a1", "holder", 60_000, 11_000);
assert.deepEqual(snap.messages.map((m) => [m.seq, m.decision]), [[1, "refused"], [2, "denied"]]);
});
const plantRow = hooks?.plantRow;
if (plantRow !== undefined) {
const SENTINEL = "planted-marker-1023";
const parked = (seq) => ({ seq, id: `r${seq}`, content: `message ${seq}`, sentAt: 100 + seq });
const damaged = [
["content retyped", { seq: 2, id: "r2", content: 7, sentAt: 102, from: SENTINEL }],
["hopChain not a list", { seq: 2, id: "r2", content: SENTINEL, sentAt: 102, hopChain: 42 }],
["sentAt missing", { seq: 2, id: "r2", content: SENTINEL }],
];
const codeOf = (e) => (typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined);
const refused = (e) => codeOf(e) === MAILBOX_ROW_MALFORMED_CODE && !thrownText(e).includes(SENTINEL);
for (const [what, bad] of damaged) {
run(`damaged record (${what}): delivery stops in front of it — the record before it is leased and acknowledged; nothing at or past it is leased, acknowledged, counted or moved (refused in the family code, quoting nothing planted); its id is not taken in as received`, async (make) => {
const s = await plantRow(make(), { scope: S, handle: "a1" }, [parked(1), bad, parked(3)]);
try {
const lease = await s.claimLease(S, "a1", "owner-1", 60_000, 1_000);
assert.deepEqual(lease?.messages.map((m) => m.seq), [1], "the record before it is leased, nothing at or past it");
assert.equal(await s.peekCount(S, "a1"), 1, "the count is the readable prefix");
await assert.rejects(s.ack(S, "a1", "owner-1", 3), refused, "an ack past it is refused");
assert.equal(await s.peekCount(S, "a1"), 1, "and nothing was consumed");
assert.deepEqual(await s.ack(S, "a1", "owner-1", 1), { acked: true });
assert.equal(await s.peekCount(S, "a1"), 0);
assert.equal(await s.claimLease(S, "a1", "owner-1", 60_000, 2_000), null, "the box stops in front of it");
await assert.rejects(s.moveDecision(S, "a1", 2, undefined, "held"), refused, "a decision move on it is refused");
await assert.rejects(s.append(S, "a1", { id: "r2", content: "message 2", sentAt: 102 }), (e) => codeOf(e) === MAILBOX_DUPLICATE_RECORD_ID_CODE && thrownText(e).includes("already holds"), "its id is still held — never answered as received");
}
finally {
s.close?.();
}
});
}
}
await settle();
}
export async function mailboxAckOwnershipContract(mk, runAssertion) {
const { run: runRaw, settle } = beginContract(runAssertion);
const run = (name, fn) => runRaw(name, () => withStores(mk, fn));
const S = MAILBOX_CONTRACT_SCOPE;
run("a non-holder's ack does not delete messages held under another owner's LIVE lease", async (make) => {
const s = make();
await s.append(S, "a1", { content: "m1", sentAt: 1 });
await s.append(S, "a1", { content: "m2", sentAt: 2 });
const lease = await s.claimLease(S, "a1", "consumer-A", 60_000, 10_000);
assert.equal(lease?.messages.length, 2);
await s.ack(S, "a1", "stale-actor", lease.maxSeq);
assert.equal(await s.peekCount(S, "a1"), 2, "the messages must survive — this caller never held the lease");
});
run("angle 4 — internal consistency: releaseLease and ack now apply the SAME owner fence (was the asymmetry that proved this was an oversight)", async (make) => {
const s = make();
await s.append(S, "a1", { content: "m1", sentAt: 1 });
await s.claimLease(S, "a1", "real-owner", 60_000, 10_000);
await s.releaseLease(S, "a1", "wrong-owner");
await s.ack(S, "a1", "wrong-owner", 1);
assert.equal(await s.peekCount(S, "a1"), 1, "neither operation should have touched anything");
});
run("angle 5 — ack with no lease EVER claimed is a no-op, not a silent wipe", async (make) => {
const s = make();
await s.append(S, "a1", { content: "m1", sentAt: 1 });
await s.ack(S, "a1", "nobody", Number.MAX_SAFE_INTEGER);
assert.equal(await s.peekCount(S, "a1"), 1);
});
run("the legitimate holder's own ack still works (regression check — the fix must not break the happy path)", async (make) => {
const s = make();
await s.append(S, "a1", { content: "m1", sentAt: 1 });
await s.append(S, "a1", { content: "m2", sentAt: 2 });
const lease = await s.claimLease(S, "a1", "consumer-A", 60_000, 10_000);
await s.ack(S, "a1", "consumer-A", lease.maxSeq);
assert.equal(await s.peekCount(S, "a1"), 0);
});
run("angle 3 in detail — the real loss sequence (stale owner outlives its own expired lease, a NEW owner has since taken over): the new owner's custody survives", async (make) => {
const s = make();
await s.append(S, "a1", { content: "ship-the-release", sentAt: 1 });
await s.append(S, "a1", { content: "notify-oncall", sentAt: 2 });
const leaseA = await s.claimLease(S, "a1", "consumer-A", 1_000, 1_000);
assert.equal(leaseA?.messages.length, 2);
const leaseB = await s.claimLease(S, "a1", "consumer-B", 60_000, 5_000);
assert.equal(leaseB?.messages.length, 2);
await s.ack(S, "a1", "consumer-A", leaseA.maxSeq);
assert.equal(await s.peekCount(S, "a1"), 2, "B's live custody must survive A's stale ack");
await s.ack(S, "a1", "consumer-B", leaseB.maxSeq);
assert.equal(await s.peekCount(S, "a1"), 0);
});
await settle();
}
export async function mailboxBundledOnlyContract(mk, runAssertion) {
const { run: runRaw, settle } = beginContract(runAssertion);
const run = (name, fn) => runRaw(name, () => withStores(mk, fn));
run("handle 含 NUL 被两个后端一致拒绝,且不得跨 (scope,handle) 串箱", async (make) => {
const s = make();
const NUL = String.fromCharCode(0);
await assert.rejects(s.append("s", `a${NUL}b`, msg("secret")));
assert.equal(await s.peekCount(`s${NUL}a`, "b"), 0, "歧义键下不得出现串箱可读");
await s.append("s", "plain", msg("ok"));
assert.equal(await s.peekCount("s", "plain"), 1);
});
run("多租户:同名 handle 在不同 scope 下是两个互不可见的箱(各自独立铸 seq)", async (make) => {
const s = make();
assert.equal(await s.append("tenant-a", "shared-handle", msg("for-a")), 1);
assert.equal(await s.append("tenant-b", "shared-handle", msg("for-b")), 1, "另一个 scope 的箱独立铸号");
assert.equal(await s.peekCount("tenant-a", "shared-handle"), 1);
const a = await s.claimLease("tenant-a", "shared-handle", "w", 60_000, 10_000);
assert.deepEqual(a.messages.map((m) => m.content), ["for-a"]);
const b = await s.claimLease("tenant-b", "shared-handle", "w", 60_000, 10_000);
assert.deepEqual(b.messages.map((m) => m.content), ["for-b"]);
await s.ack("tenant-a", "shared-handle", "w", a.maxSeq);
assert.equal(await s.peekCount("tenant-a", "shared-handle"), 0);
assert.equal(await s.peekCount("tenant-b", "shared-handle"), 1, "跨 scope 的 ack 不得越界");
await s.drop("tenant-b", "shared-handle");
assert.equal(await s.peekCount("tenant-b", "shared-handle"), 0);
});
run("匿名工作区是普通的一格:ANONYMOUS_SCOPE 下的箱换任何别的名字都读不到,具名格的箱也不在它下面", async (make) => {
const s = make();
assert.equal(await s.append(ANONYMOUS_SCOPE, "shared-handle", msg("for-anon")), 1);
assert.equal(await s.append("tenant-a", "shared-handle", msg("for-a")), 1);
const anon = await s.claimLease(ANONYMOUS_SCOPE, "shared-handle", "w", 60_000, 10_000);
assert.deepEqual(anon.messages.map((m) => m.content), ["for-anon"]);
const named = await s.claimLease("tenant-a", "shared-handle", "w", 60_000, 10_000);
assert.deepEqual(named.messages.map((m) => m.content), ["for-a"]);
assert.equal(await s.peekCount("tenant-z", "shared-handle"), 0, "别的名字读不到匿名箱");
});
run("第四条消费链(principal 收件箱):投递门铸的信落收件人 scope 的 principal.inbox,两只信任锚逐字节回读,发信方 scope 零残留", async (make) => {
const s = make();
const letter = mintCrossPrincipalRecord({ from: { scope: "principal-a", name: "alice" }, body: { content: "letter" }, receiptId: "gr-1", sentAt: 10_000, consumer: { kind: "terminals" } });
assert.equal(await s.append("principal-b", PRINCIPAL_INBOX_HANDLE, letter), 1);
assert.equal(await s.peekCount("principal-a", PRINCIPAL_INBOX_HANDLE), 0, "发信方 scope 的同名箱不得出现这封信");
const lease = await s.claimLease("principal-b", PRINCIPAL_INBOX_HANDLE, "drain:r1", 60_000, 10_000);
assert.deepEqual(lease.messages.map((m) => m.peerMeta), [{ kind: "peer_message", fromScope: "principal-a", gateReceiptId: "gr-1" }]);
assert.equal(lease.messages[0].from, "alice");
assert.deepEqual(await s.ack("principal-b", PRINCIPAL_INBOX_HANDLE, "drain:r1", lease.maxSeq), { acked: true });
assert.equal(await s.peekCount("principal-b", PRINCIPAL_INBOX_HANDLE), 0);
});
await settle();
}
export async function mailboxCrossProcessContract(hooks) {
const { run: runRaw, settle } = beginContract(hooks.runAssertion);
const run = (name, fn) => runRaw(name, async () => {
const pair = await hooks.openPair();
try {
await fn(pair.local, pair.peer);
}
finally {
await pair.dispose();
}
});
const S = MAILBOX_CONTRACT_SCOPE;
const H = "session.shared";
const range = (n) => Array.from({ length: n }, (_, i) => i + 1);
run("跨进程 seq 单铸:两个进程交错 append N+N ⇒ seq 恰为 1..2N(无重复无空洞),每条消息在任一方视角都可见", async (local, peer) => {
const N = 40;
const seqs = [];
for (let i = 0; i < N; i++) {
const [a, b] = await Promise.all([local.append(S, H, msg(`local-${i}`, 1_000 + i)), peer.append(S, H, msg(`peer-${i}`, 2_000 + i))]);
seqs.push(a, b);
}
assert.deepEqual([...seqs].sort((x, y) => x - y), range(2 * N), "两方拿到的回执合起来必须恰是 1..2N");
assert.equal(await peer.peekCount(S, H), 2 * N, "对方进程的观察面必须看到本方的 append");
assert.equal(await local.peekCount(S, H), 2 * N);
const lease = await local.claimLease(S, H, "cycle-1", 60_000, 10_000);
assert.deepEqual(lease.messages.map((m) => m.seq), range(2 * N), "本方 claim 必须按 seq 序取到全部 2N 条");
assert.equal(lease.maxSeq, 2 * N);
const contents = new Set(lease.messages.map((m) => m.content));
for (let i = 0; i < N; i++) {
assert.ok(contents.has(`local-${i}`), `local-${i} 不得丢`);
assert.ok(contents.has(`peer-${i}`), `peer-${i} 不得丢`);
}
});
run("lease/ack 不跨进程交叉:一方的活租约 fence 住另一方的 claim;非持有方的 ack 是 no-op;持有方的 ack 对另一方立即可见;高水位跨对方的 ack 存活", async (local, peer) => {
await local.append(S, H, msg("m1", 1));
await peer.append(S, H, msg("m2", 2));
const held = await peer.claimLease(S, H, "cycle-peer", 60_000, 10_000);
assert.deepEqual(held.messages.map((m) => m.seq), [1, 2]);
assert.equal(await local.claimLease(S, H, "cycle-local", 60_000, 11_000), null, "对方进程的活租约必须 fence 住本方");
await local.ack(S, H, "cycle-local", held.maxSeq);
assert.equal(await peer.peekCount(S, H), 2, "非持有方的 ack 不得动持有方手上的批");
await peer.ack(S, H, "cycle-peer", held.maxSeq);
assert.equal(await local.peekCount(S, H), 0, "持有方的 ack 必须被本方看见");
assert.equal(await local.claimLease(S, H, "cycle-local", 60_000, 12_000), null);
assert.equal(await local.append(S, H, msg("m3", 3)), 3, "seq 高水位必须跨对方进程的 ack 存活(永不复用)");
await peer.append(S, H, msg("m4", 4));
const held2 = await peer.claimLease(S, H, "cycle-peer-2", 1_000, 20_000);
assert.deepEqual(held2.messages.map((m) => m.seq), [3, 4]);
const takeover = await local.claimLease(S, H, "cycle-local-2", 60_000, 30_000);
assert.deepEqual(takeover.messages.map((m) => m.seq), [3, 4], "过期租约的接管跨进程成立,seq 原样");
});
run("交出之后的出口跨进程只归持租者:本方交出后租约过期、对方进程接手,本方迟到的 delivered → dropped 被拒;对方的结清本方看得见", async (local, peer) => {
await local.append(S, H, msg("m1", 1));
assert.ok(await local.claimLease(S, H, "cycle-local", 1_000, 10_000));
assert.deepEqual(await local.moveDecision(S, H, 1, undefined, "held", "cycle-local"), { ok: true });
assert.deepEqual(await local.moveDecision(S, H, 1, "held", "delivered", "cycle-local"), { ok: true });
const taken = await peer.claimLease(S, H, "cycle-peer", 60_000, 20_000);
assert.deepEqual(taken.messages.map((m) => m.decision), ["delivered"], "对方接手时看到 delivered");
assert.deepEqual(await local.moveDecision(S, H, 1, "delivered", "dropped", "cycle-local"), { ok: false, current: "delivered" }, "对方进程写下的租约必须在本方的这一步里被读到");
assert.deepEqual(await peer.moveDecision(S, H, 1, "delivered", "dropped", "cycle-peer"), { ok: true }, "当前持租者结清");
const seen = await local.claimLease(S, H, "cycle-local-2", 60_000, 90_000);
assert.deepEqual(seen.messages.map((m) => m.decision), ["dropped"], "对方的结清本方看得见");
});
run("一方的 housekeeping 不丢另一方的 append:两进程各自反复压缩/重写期间交错写入 120 条,任一方视角都完整", async (local, peer) => {
const N = 60;
for (let i = 0; i < N; i++) {
await Promise.all([local.append(S, H, msg(`L${i}`, 1_000 + i)), peer.append(S, H, msg(`P${i}`, 2_000 + i))]);
}
const fromPeer = await peer.claimLease(S, H, "cycle-peer", 60_000, 10_000);
assert.deepEqual(fromPeer.messages.map((m) => m.seq), range(2 * N), "对方视角:seq 1..2N 全在");
await peer.releaseLease(S, H, "cycle-peer");
const fromLocal = await local.claimLease(S, H, "cycle-local", 60_000, 11_000);
assert.deepEqual(fromLocal.messages.map((m) => m.seq), range(2 * N), "本方视角:seq 1..2N 全在");
const contents = fromLocal.messages.map((m) => m.content).sort();
assert.deepEqual(contents, [...range(N).map((i) => `L${i - 1}`), ...range(N).map((i) => `P${i - 1}`)].sort());
await local.ack(S, H, "cycle-local", fromLocal.maxSeq);
assert.equal(await peer.peekCount(S, H), 0, "本方的 ack 对方可见");
});
run("reap 看得见对方进程的旧消息,哪怕本方缓存里这个箱是空的(已加载的空缓存不得替对方的旧消息说「没有」)", async (local, peer) => {
await local.append(S, H, msg("mine", 1_000));
const held = await local.claimLease(S, H, "cycle-local", 60_000, 1_000);
await local.ack(S, H, "cycle-local", held.maxSeq);
await peer.append(S, H, msg("old-from-peer", 2_000));
assert.equal(await local.reap(S, 100_000, { maxAgeMs: 50_000 }), 1, "对方写的过期消息必须被本方 reap 看见并老化");
assert.equal(await peer.peekCount(S, H), 0);
assert.equal(await peer.append(S, H, msg("after", 200_000)), 3, "高水位跨 reap 存活(对方视角)");
});
run("W7 已收窗跨进程:一方 append + ack 带 id 的 X,另一方同记录 append(X) ⇒ 首个 seq 零写;异记录 ⇒ 带码拒", async (local, peer) => {
const x = { id: "frame-x", from: "w", content: "status", sentAt: 1_000, hopChain: ["h"], peerMeta: { kind: "peer_message", fromRoot: "root" } };
assert.equal(await local.append(S, H, x), 1);
const held = await local.claimLease(S, H, "cycle-local", 60_000, 10_000);
assert.deepEqual(await local.ack(S, H, "cycle-local", held.maxSeq), { acked: true });
assert.equal(await peer.append(S, H, { ...x, sentAt: 5_000 }), 1, "对方进程看得见本方收进窗的记录:同记录回首个 seq");
assert.equal(await peer.peekCount(S, H), 0, "零写");
let code;
try {
await peer.append(S, H, { ...x, content: "another" });
}
catch (e) {
code = e.code;
}
assert.equal(code, MAILBOX_DUPLICATE_RECORD_ID_CODE);
});
run("replayOf 跨进程:一方 append(未收)与 append + ack(已收窗)的带 id 记录,另一方的 replayOf 都答首个 seq、零写;异记录 ⇒ 带码拒;未知记录 ⇒ undefined", async (local, peer) => {
const mk = (id, content = "status") => ({ id, from: "w", content, sentAt: 1_000, hopChain: ["h"], peerMeta: { kind: "peer_message", fromRoot: "root" } });
assert.equal(await local.append(S, H, mk("held-x")), 1);
assert.equal(await peer.replayOf(S, H, { ...mk("held-x"), sentAt: 5_000 }), 1, "对方进程看得见本方持有的记录");
const lease = await local.claimLease(S, H, "cycle-local", 60_000, 10_000);
assert.deepEqual(await local.ack(S, H, "cycle-local", lease.maxSeq), { acked: true });
assert.equal(await peer.replayOf(S, H, mk("held-x")), 1, "对方进程看得见本方收进窗的记录");
assert.equal(await peer.replayOf(S, H, mk("never-seen")), undefined);
assert.equal(await peer.peekCount(S, H), 0, "零写");
let code;
try {
await peer.replayOf(S, H, mk("held-x", "another"));
}
catch (e) {
code = e.code;
}
assert.equal(code, MAILBOX_DUPLICATE_RECORD_ID_CODE);
});
run("reap 与 drop 的 seq 语义跨进程:一方 reap 后另一方继续高水位;一方 drop 后另一方从 1 重铸", async (local, peer) => {
await peer.append(S, H, msg("old", 1_000));
assert.equal(await local.reap(S, 100_000, { maxAgeMs: 50_000 }), 1, "本方 reap 必须看见对方写的旧消息");
assert.equal(await peer.peekCount(S, H), 0);
assert.equal(await peer.append(S, H, msg("after-reap", 200_000)), 2, "reap 清箱但保高水位(跨进程)");
await local.drop(S, H);
assert.equal(await peer.peekCount(S, H), 0, "本方 drop 对方可见");
assert.equal(await peer.append(S, H, msg("after-drop", 300_000)), 1, "drop 结束箱的一生:对方从 1 重铸");
assert.equal(await local.peekCount(S, H), 1);
});
await settle();
}
export async function mailboxTombstonedRecipientContract(mk, hooks) {
const { run: runRaw, settle } = beginContract(hooks.runAssertion);
const run = (name, fn) => runRaw(name, () => withStores(mk, fn));
const S = MAILBOX_CONTRACT_SCOPE;
const codeOf = (e) => e?.code;
const tombstone = async (s, scope, handle) => {
const pair = mailboxRecipientLifecycleOf(s);
if (pair === undefined) {
assert.notEqual(hooks.tombstone, undefined, "nothing puts a recipient into the pre-delete state: the store carries no retireRecipient and no tombstone hook was given");
return hooks.tombstone(s, scope, handle);
}
assert.equal(await pair.retireRecipient(scope, handle, 1_000_000, "label"), true, "retireRecipient answers true when it wrote the tombstone");
};
run("收件人生命周期一对成员是一项能力:要么都在、要么都缺;都在时不再另收 tombstone 钩子(同一个态不许两种写法)", async (make) => {
let carriesPair = false;
try {
carriesPair = mailboxRecipientLifecycleOf(make()) !== undefined;
}
catch (e) {
assert.fail(`the store's recipient-lifecycle pair cannot be read: ${thrownText(e)}`);
}
assert.equal(carriesPair && hooks.tombstone !== undefined, false, "the store writes its own pre-delete state (retireRecipient), so a tombstone hook is a second way to write it");
assert.equal(carriesPair || hooks.tombstone !== undefined, true, "nothing puts a recipient into the pre-delete state: no retireRecipient on the store and no tombstone hook");
});
run("收件人生命周期一对(可选成员):在则逐条验 —— 只打标、列表、重写、随箱亡;缺席如实上报,不算失败", async (make) => {
const pair = mailboxRecipientLifecycleOf(make());
if (pair === undefined) {
hooks.onOptionalMember?.({ member: "recipientLifecycle", status: "absent" });
return;
}
const listed = make();
const lp = mailboxRecipientLifecycleOf(listed);
assert.equal(await lp.retireRecipient(S, "session.a1", 5_000, "Plan"), true, "retireRecipient answers true when it wrote the tombstone");
await lp.retireRecipient(S, "agent.b1", 6_000);
await lp.retireRecipient("tenant-b", "session.c1", 7_000);
assert.deepEqual(await lp.listRetiredRecipients(S, "session."), [{ handle: "session.a1", retiredAt: 5_000, label: "Plan" }], "清单按 (scope, 前缀) 列出 handle / retiredAt / label");
assert.deepEqual(await lp.listRetiredRecipients(S, "agent."), [{ handle: "agent.b1", retiredAt: 6_000 }], "清单按 (scope, 前缀):no label ⇒ no label member");
assert.deepEqual(await lp.listRetiredRecipients("tenant-b", "agent."), [], "清单按 (scope, 前缀):a prefix lists only its own handles, in its own scope");
const again = make();
const ap = mailboxRecipientLifecycleOf(again);
await ap.retireRecipient(S, "session.a1", 5_000, "old");
await ap.retireRecipient(S, "session.a1", 9_000, "new");
assert.deepEqual(await ap.listRetiredRecipients(S, "session."), [{ handle: "session.a1", retiredAt: 9_000, label: "new" }], "重复 retire 更新时刻与名字,清单里仍是一行");
const dropped = make();
const dp = mailboxRecipientLifecycleOf(dropped);
await dropped.append(S, "session.a1", msg("before"));
await dp.retireRecipient(S, "session.a1", 5_000);
await assert.rejects(dropped.append(S, "session.a1", msg("refused")), (e) => codeOf(e) === MAILBOX_TOMBSTONED_RECIPIENT_CODE);
await dropped.drop(S, "session.a1");
assert.deepEqual(await dp.listRetiredRecipients(S, "session."), [], "墓碑随箱亡:drop removes the tombstone with the box");
assert.equal(await dropped.append(S, "session.a1", msg("registered again")), 1, "墓碑随箱亡:an id registered again is a new recipient (seq 1)");
hooks.onOptionalMember?.({ member: "recipientLifecycle", status: "verified" });
});
run("预删除态的收件人:append 响亮拒且带码(既不静默收下级联即将删掉的消息,也不裸抛)", async (make) => {
const s = make();
await tombstone(s, S, "a1");
let thrown;
try {
await s.append(S, "a1", msg("m1"));
}
catch (e) {
thrown = e;
}
assert.notEqual(thrown, undefined, "静默收下 = 给发件人一张级联马上撕掉的回执");
assert.equal(codeOf(thrown), MAILBOX_TOMBSTONED_RECIPIENT_CODE, "裸抛与拒同形:消费方要能按码分诊");
let again;
try {
await s.append(S, "a1", msg("m2"));
}
catch (e) {
again = e;
}
assert.equal(codeOf(again), MAILBOX_TOMBSTONED_RECIPIENT_CODE);
});
run("拒的粒度是收件人,不是开关:同 scope 下另一个活收件人照常收信", async (make) => {
const s = make();
await tombstone(s, S, "a1");
assert.equal(await s.append(S, "a2", msg("still-live")), 1, "活收件人不受邻居的删除级联牵连");
assert.equal(await s.peekCount(S, "a2"), 1);
});
run("收件人身份是 (scope, handle) 整体:A 租户的删除级联不得拒掉 B 租户的同名收件人", async (make) => {
const s = make();
await tombstone(s, "tenant-a", "a1");
assert.equal(await s.append("tenant-b", "a1", msg("other-tenant")), 1, "同名 handle 在另一个租户下是另一个收件人");
assert.equal(await s.peekCount("tenant-b", "a1"), 1);
});
run("两件套还得是单射的:把 (scope, handle) 拼成一个字符串记态,不得让两个不同收件人撞成一个", async (make) => {
const s = make();
await tombstone(s, "tenant a", "b");
assert.equal(await s.append("tenant", "a b", msg("distinct-recipient")), 1, "拼键歧义不得把另一个收件人一起拒掉");
assert.equal(await s.peekCount("tenant", "a b"), 1);
});
run("副作用轴 · 活租约:被拒的 append 不得动别人手上的租约(单消费者围栏不因删除窗口松开)", async (make) => {
const s = make();
await s.append(S, "a1", msg("in-flight"));
const held = await s.claimLease(S, "a1", "consumer-A", 60_000, 10_000);
assert.equal(held?.messages.length, 1);
await tombstone(s, S, "a1");
await assert.rejects(s.append(S, "a1", msg("after-tombstone", 2_000)), "预删除态下的 append 必须拒");
assert.equal(await s.claimLease(S, "a1", "rival", 60_000, 11_000), null, "A 的活租约必须仍然 fence 住别人");
await s.ack(S, "a1", "consumer-A", held.maxSeq);
assert.equal(await s.peekCount(S, "a1"), 0);
});
run("拒的是入口,不是清仓:被拒的 append 零副作用,已入箱的消息按原 seq/内容原封不动", async (make) => {
const s = make();
const seq = await s.append(S, "a1", msg("parked-before"));
await tombstone(s, S, "a1");
let thrown;
let refused = false;
try {
await s.append(S, "a1", msg("after-tombstone", 2_000));
}
catch (e) {
refused = true;
thrown = e;
}
assert.equal(refused, true, "预删除态下的 append 必须拒");
assert.equal(codeOf(thrown), MAILBOX_TOMBSTONED_RECIPIENT_CODE, "箱非空时的拒同样要带码");
assert.equal(await s.peekCount(S, "a1"), 1, "被拒的 append 不得入箱(幽灵投递),也不得清箱");
const lease = await s.claimLease(S, "a1", "w1", 60_000, 10_000);
assert.deepEqual(lease?.messages.map((m) => m.seq), [seq]);
assert.deepEqual(lease?.messages.map((m) => m.content), ["parked-before"], "取到的仍是拒之前那一条");
});
await settle();
}