diff --git a/crates/spoke-connect/src/remote/responder.rs b/crates/spoke-connect/src/remote/responder.rs index a0ec16b3..cf3b3a63 100644 --- a/crates/spoke-connect/src/remote/responder.rs +++ b/crates/spoke-connect/src/remote/responder.rs @@ -97,7 +97,7 @@ use crate::remote::remote_adapter::{ RemoteErrorKind as ResponderErrorKind, RemoteIdentity, ToolHandler, }; use crate::remote::serve_ports::{ - exact_revision_u64, schema_versions_in_domain, RemoteServePorts, + exact_revision_u64, schema_versions_in_domain, RemoteServePorts, HISTORY_OP_GET, }; use crate::remote::transport::Transport; use crate::remote::{ @@ -998,10 +998,11 @@ fn history_uncertain_reject(budget: Duration) -> SpokeReject { } /// §14.2/§14.3: the detached history invoke panicked (or otherwise -/// dropped its result channel) AFTER invocation, so the transport has no -/// evidence that nothing committed — a clean `INTERNAL_ERROR` would -/// assert no-effect. The response says the outcome is unknown instead -/// (same containment as the memory panic path). +/// dropped its result channel) during invocation, so the transport has no +/// evidence that nothing committed — it cannot tell a pre-effect panic from +/// one after a committed write, and a clean `INTERNAL_ERROR` would assert +/// no-effect. The response says the outcome is unknown instead (same +/// containment as the memory panic path). fn history_panic_uncertain_reject() -> SpokeReject { let mut details = Map::new(); details.insert("retry_class".into(), Value::String("uncertain".into())); @@ -2199,13 +2200,16 @@ impl ConnectResponder { /// without providing the service). /// /// The serve bound matches the `memory.*` ops: a zero budget answers - /// the plain timeout without invoking the service at all, while - /// expiry AFTER invocation means the admitted mutation may have - /// committed — that is `OUTCOME_UNCERTAIN`/`uncertain` - /// (§14.2/§14.3), recoverable through the service's recorded-outcome - /// dedup, never a clean internal error or a silent re-execution. The - /// service task keeps running past the deadline so a settling prune - /// still records its outcome. + /// the plain timeout without invoking the service at all. Past + /// invocation the ops split by effect (`HISTORY_OP_GET` is read-only, + /// `history.revisions.prune` mutates): an expired budget or a dropped + /// result channel on a read answers the plain serve timeout / + /// internal error, while on a prune it stays + /// `OUTCOME_UNCERTAIN`/`uncertain` (§14.2/§14.3) — the admitted + /// mutation may have committed, recoverable through the service's + /// recorded-outcome dedup, never a clean internal error or a silent + /// re-execution. The service task keeps running past the deadline so + /// a settling prune still records its outcome. async fn dispatch_history_invoke( &self, doc: &Value, @@ -2259,15 +2263,19 @@ impl ConnectResponder { return Ok(()); }; // Same serve bound as `memory.*`: a zero budget rejects before the - // service is invoked (the baseline serve-timeout rejection - // stands). A non-zero budget that expires AFTER invocation means - // the mutation may have committed: that is `OUTCOME_UNCERTAIN`, - // not a clean internal error. The admitted invoke is detached - // from the response deadline (spawned, matching the TS path's - // uncancellable promise): expiry answers the budget, it never - // cancels the provider task, and the dedup store still records - // the settled outcome for a same-key replay to recover. + // service is invoked (the baseline serve-timeout rejection stands). + // Past invocation only the read op is plain: `history.revisions.get` + // cannot commit, so an expired budget or a dropped result channel + // answers the plain serve timeout / internal error. Only the prune — + // the one registered mutating op — stays conservative: a dropped + // channel cannot tell a pre-effect panic from a committed write, so + // the same failures are `OUTCOME_UNCERTAIN`. The + // admitted invoke is detached from the response deadline (spawned, + // matching the TS path's uncancellable promise): expiry answers the + // budget, it never cancels the provider task, and the dedup store + // still records the settled outcome for a same-key replay to recover. let zero_budget = self.invoke_timeout.is_zero(); + let is_read = op == HISTORY_OP_GET; let bounded = if zero_budget { None } else { @@ -2281,11 +2289,22 @@ impl ConnectResponder { match tokio::time::timeout(self.invoke_timeout, rx).await { Ok(Ok(result)) => Some(result), // The detached task sends exactly once before dropping the - // sender; a receive failure means it panicked AFTER - // admission, so — like a budget expiry — the transport - // cannot assert no-effect (§14.3): answer uncertain, - // never a clean internal error. - Ok(Err(_)) => Some(SpokeResult::Reject(history_panic_uncertain_reject())), + // sender; a receive failure means the service panicked during + // invocation. The responder observes only the dropped channel, + // so — on a prune — it cannot tell a pre-effect panic from a + // possibly committed write (§14.3): answer uncertain, never a + // clean internal error. A read has no effect to be uncertain + // about. + Ok(Err(_)) => Some(SpokeResult::Reject(if is_read { + SpokeReject { + code: SpokeRejectCode::InternalError, + message: "history service failed after invocation: result channel dropped" + .to_string(), + details: None, + } + } else { + history_panic_uncertain_reject() + })), Err(_) => None, } }; @@ -2293,7 +2312,7 @@ impl ConnectResponder { return Ok(()); } let Some(result) = bounded else { - let reject = if zero_budget { + let reject = if zero_budget || is_read { serve_timeout_reject(self.invoke_timeout) } else { history_uncertain_reject(self.invoke_timeout) diff --git a/crates/spoke-connect/tests/remote_loopback.rs b/crates/spoke-connect/tests/remote_loopback.rs index 44ac435d..8d0da710 100644 --- a/crates/spoke-connect/tests/remote_loopback.rs +++ b/crates/spoke-connect/tests/remote_loopback.rs @@ -52,8 +52,9 @@ use spoke_connect::remote::{ reset_accepted_server_hellos_for_test, ConnectResponder, ConnectResponderOptions, HistoryPortService, LoopbackTransport, LoopbackTransportPair, MultiPeerRouterOptions, RemoteAdapter, RemoteAdapterError, RemoteAdapterOptions, RemoteAdapterState, - RemoteExtractService, RemoteIdentity, RemoteKnowledgeFace, RemoteScopedKnowledgeFace, - RemoteServePorts, RemoteServePortsComposite, ToolHandler, Transport, TransportError, + RemoteExtractService, RemoteHistoryService, RemoteIdentity, RemoteKnowledgeFace, + RemoteScopedKnowledgeFace, RemoteServePorts, RemoteServePortsComposite, ToolHandler, Transport, + TransportError, }; use spoke_fixture_toy_world::ToyWorldAdapter; use spoke_operations::{ @@ -8374,6 +8375,19 @@ impl HistoryPort for UnreachedHistoryPort { } } +/// A raw history face that panics during invocation, so the responder's +/// detached task dies before sending: the only thing the responder can +/// observe is a dropped result channel, never whether the panic hit before +/// or after any side effect. +struct DroppedChannelHistoryService; + +#[async_trait] +impl RemoteHistoryService for DroppedChannelHistoryService { + async fn invoke(&self, _peer: &str, _op: &str, _payload: Value) -> SpokeResult { + panic!("history service panicked during invocation"); + } +} + /// A1 blocking-pool requirement: a request-scoped admission is host work that /// may block, so it runs off the async worker. On a CURRENT-THREAD runtime a /// gated scoped admission must not stop the responder from answering its serve @@ -8466,11 +8480,15 @@ async fn a_gated_scoped_history_admission_still_answers_the_serve_timeout() { .await .expect("the serve budget answers while the scoped admission is still gated"); - assert_eq!(response["error"]["code"], "OUTCOME_UNCERTAIN", "{response}"); + assert_eq!(response["error"]["code"], "INTERNAL_ERROR", "{response}"); assert_eq!( - response["error"]["details"]["retry_class"], "uncertain", + response["error"]["details"]["kind"], "timeout", "{response}" ); + assert!( + response["error"]["details"].get("retry_class").is_none(), + "a read must not claim an uncertain outcome: {response}" + ); assert!( entered.load(Ordering::SeqCst), "the scoped admission really ran" @@ -8490,6 +8508,99 @@ async fn a_gated_scoped_history_admission_still_answers_the_serve_timeout() { responder.close(); } +/// A read that dies during invocation has no effect to be uncertain about: +/// the responder observes only a dropped result channel and answers the +/// plain internal error, with no details. +#[tokio::test] +async fn a_panicking_history_get_answers_a_plain_internal_error() { + let ports: Arc = Arc::new( + RemoteServePortsComposite::new( + Arc::new(ToyWorldAdapter::with_committed_fixtures()), + None, + None, + ) + .with_history(Arc::new(DroppedChannelHistoryService)), + ); + let (responder, pair, seed) = + start_raw_ke_responder_with_budget(ports, &["spoke-history"], Some(500)).await; + let session = raw_handshake( + &pair.client, + seed, + &ke_remote_manifest("test-client", &["spoke-history"]), + ) + .await; + + let response = raw_invoke( + &pair.client, + seed, + &session, + 0, + "panicking-history-get", + "history.revisions.get", + json!({ + "entity_kind": "knowledge_entry", + "entity_id": "e1", + "revision": 1, + }), + ) + .await; + + assert_eq!(response["error"]["code"], "INTERNAL_ERROR", "{response}"); + assert!( + response["error"].get("details").is_none(), + "a read failure carries no details: {response}" + ); + responder.close(); +} + +/// A prune that dies during invocation may already have committed: the +/// responder observes only a dropped result channel, so it keeps the +/// conservative uncertain answer, covering both a pre-effect panic and a +/// possibly committed write. +#[tokio::test] +async fn a_panicking_history_prune_stays_uncertain() { + let ports: Arc = Arc::new( + RemoteServePortsComposite::new( + Arc::new(ToyWorldAdapter::with_committed_fixtures()), + None, + None, + ) + .with_history(Arc::new(DroppedChannelHistoryService)), + ); + let (responder, pair, seed) = + start_raw_ke_responder_with_budget(ports, &["spoke-history"], Some(500)).await; + let session = raw_handshake( + &pair.client, + seed, + &ke_remote_manifest("test-client", &["spoke-history"]), + ) + .await; + + let response = raw_invoke( + &pair.client, + seed, + &session, + 0, + "panicking-history-prune", + "history.revisions.prune", + json!({ + "entity_kind": "knowledge_entry", + "entity_id": "e1", + "keep": 2, + "idempotency_key": "panic-prune", + }), + ) + .await; + + assert_eq!(response["error"]["code"], "OUTCOME_UNCERTAIN", "{response}"); + assert_eq!( + response["error"]["details"]["retry_class"], "uncertain", + "{response}" + ); + assert_eq!(response["error"]["details"]["kind"], "panic", "{response}"); + responder.close(); +} + /// QC2-02: a scoped admission that panics is contained, and the join payload — /// which carries the callback's panic text — never reaches the wire. #[tokio::test] diff --git a/docs/reference/history.md b/docs/reference/history.md index 5bf4a12a..f548b6c0 100644 --- a/docs/reference/history.md +++ b/docs/reference/history.md @@ -96,8 +96,11 @@ The Connect serving face is `RemoteHistoryService` over a provider `HistoryPort` | `STORED_REVISION_STALE` | A conditional entity put names an `expected_base_revision` that does not equal the current row revision; history floor state plays no part | The entity's existing stale-revision details, for example `{ "expectedBaseRevision": 1, "storeRevision": 5 }` | | `IDEMPOTENCY_CONFLICT` | A prune retry reuses the same key with a different payload digest | None | | `RECEIPT_EXPIRED` | A prune retry replays a key whose recorded outcome was evicted | None | -| `INTERNAL_ERROR` | A zero serve budget refuses before the history service is invoked; the provider was never called | `{ "kind": "timeout" }` | -| `OUTCOME_UNCERTAIN` | A non-zero serve budget expires after invocation, or the service fails after invocation; the provider outcome is unknown | `{ "retry_class": "uncertain", "kind": "timeout" \| "panic" }` | +| `INTERNAL_ERROR` | `history.revisions.get`: a zero serve budget refuses before the history service is invoked; a non-zero budget that expires after invocation answers the plain serve timeout (`details.kind = "timeout"`); a thrown or failed service call — the service panics, drops its result channel, or throws — answers the plain internal error with no `details`; a malformed or wrong-target provider snapshot answers `INTERNAL_ERROR` with `details.kind = "transport"`. A rejection the service itself returns (for example `HISTORY_TRUNCATED`) passes through unchanged. The responder never generates `OUTCOME_UNCERTAIN` for a read. | `{ "kind": "timeout" }` on the budget paths; absent on a thrown or failed service call; `{ "kind": "transport" }` on a malformed or wrong-target snapshot | +| `INTERNAL_ERROR` | `history.revisions.prune`: a zero serve budget refuses before the history service is invoked; the provider was never called | `{ "kind": "timeout" }` | +| `OUTCOME_UNCERTAIN` | `history.revisions.prune`: a non-zero serve budget expires after invocation, or a transport-generated post-invocation failure — the detached invoke panics, drops its result channel, or throws; the provider outcome is unknown. A rejection the service itself returns passes through unchanged. | `{ "retry_class": "uncertain", "kind": "timeout" \| "panic" }` | + +Only the two registered ops (`history.revisions.get` and `history.revisions.prune`) reach the history face. Any other `history.*` op is refused at the capability gate — `op_unsupported`, or `capability_missing` when the op maps to a capability — before the face probe, so it never reaches invocation. `HISTORY_TRUNCATED`, `HISTORY_ENTITY_UNSUPPORTED`, and `HISTORY_NOT_RETAINED` are new `SpokeRejectCode` members; the remaining codes keep their established meanings. diff --git a/docs/zh/reference/history.md b/docs/zh/reference/history.md index 646a9fa7..386bfb97 100644 --- a/docs/zh/reference/history.md +++ b/docs/zh/reference/history.md @@ -96,8 +96,11 @@ Connect 服务面是 `RemoteHistoryService`,经 `HistoryPortService` 适配提 | `STORED_REVISION_STALE` | 条件实体 put 的 `expected_base_revision` 不等于当前行修订;历史地板状态不参与 | 实体既有的过期修订细节,例如 `{ "expectedBaseRevision": 1, "storeRevision": 5 }` | | `IDEMPOTENCY_CONFLICT` | 裁剪重试复用同一键但载荷摘要不同 | 无 | | `RECEIPT_EXPIRED` | 裁剪重试重放其记录结果已被逐出的键 | 无 | -| `INTERNAL_ERROR` | serve 预算为零,响应方在调用历史服务之前拒绝;提供方从未被调用 | `{ "kind": "timeout" }` | -| `OUTCOME_UNCERTAIN` | 非零 serve 等待在调用后超出本地预算,或调用后服务失败;提供方结果未知 | `{ "retry_class": "uncertain", "kind": "timeout" \| "panic" }` | +| `INTERNAL_ERROR` | `history.revisions.get`:serve 预算为零时在调用历史服务之前拒绝;非零预算在调用后超出本地预算时,应答普通 serve 超时(`details.kind = "timeout"`);抛出或失败的服务调用 —— 服务 panic、丢弃结果通道或抛错 —— 应答不带 `details` 的普通内部错误;畸形或目标不符的提供方快照应答 `INTERNAL_ERROR` 且 `details.kind = "transport"`。服务自身返回的拒绝(例如 `HISTORY_TRUNCATED`)原样透传。响应方对读操作绝不生成 `OUTCOME_UNCERTAIN`。 | 预算路径为 `{ "kind": "timeout" }`;抛出或失败的服务调用时 `details` 缺失;畸形或目标不符的快照为 `{ "kind": "transport" }` | +| `INTERNAL_ERROR` | `history.revisions.prune`:serve 预算为零时在调用历史服务之前拒绝;提供方从未被调用 | `{ "kind": "timeout" }` | +| `OUTCOME_UNCERTAIN` | `history.revisions.prune`:非零 serve 预算在调用后超出本地预算,或发生传输层产生的调用后失败 —— 分离的调用 panic、丢弃结果通道或抛错;提供方结果未知。服务自身返回的拒绝原样透传。 | `{ "retry_class": "uncertain", "kind": "timeout" \| "panic" }` | + +只有两个已注册操作(`history.revisions.get` 与 `history.revisions.prune`)会到达历史服务面。其它任何 `history.*` 操作在服务面探测之前即被能力门禁拒绝 —— `op_unsupported`,或该操作映射到某个能力时为 `capability_missing` —— 因此绝不会到达调用阶段。 `HISTORY_TRUNCATED`、`HISTORY_ENTITY_UNSUPPORTED` 与 `HISTORY_NOT_RETAINED` 是新增的 `SpokeRejectCode` 成员;其余代码保持既有含义。 diff --git a/packages/spoke-connect-ts/src/remote/responder.ts b/packages/spoke-connect-ts/src/remote/responder.ts index ee8e403c..38bd1641 100644 --- a/packages/spoke-connect-ts/src/remote/responder.ts +++ b/packages/spoke-connect-ts/src/remote/responder.ts @@ -2158,12 +2158,14 @@ export class ConnectResponder { * host declared `spoke-history` without providing the service). * * The serve bound matches the `memory.*` ops: a zero budget answers the - * plain timeout without invoking the service at all, while expiry AFTER - * invocation means the admitted mutation may have committed — that is + * plain timeout without invoking the service at all. Past invocation only + * the read op (`history.revisions.get`) is plain: an expired budget or a + * thrown service answers the plain serve timeout / internal error. Only + * the prune — the one registered mutating op — stays * `OUTCOME_UNCERTAIN`/`uncertain` (§14.2/§14.3), recoverable through the * recorded-outcome dedup, never a clean internal error or a silent - * re-execution. The service promise keeps running past the deadline so - * a settling prune still records its outcome. + * re-execution. The service promise keeps running past the deadline so a + * settling prune still records its outcome. */ async #dispatchHistoryInvoke(doc: ConnectInvokeRequest): Promise { const session = this.#session; @@ -2196,13 +2198,16 @@ export class ConnectResponder { // session peer, never from the payload (MEM-R003; contract // §Authorization). const peerId = this.remotePeerId; - // note: a zero budget rejects before the service is invoked (plain - // timeout, no dedup key reserved). A non-zero budget expiring AFTER - // invocation answers the uncertain outcome identically to the memory - // ops — the invoked service is left running; nothing here claims - // cancellation or rollback of provider work. + // note: a zero budget never invokes the service (plain timeout, no dedup + // key reserved). A non-zero expiry or a thrown service on + // `history.revisions.get` is a plain timeout / internal error: a read + // cannot have committed. Only the prune — the one registered mutating + // op — stays uncertain: its effect is unknown and may have committed. + const isRead = doc.op === "history.revisions.get"; + // note: only the read op is plain; the prune is the sole registered + // mutating op, so it is the only op whose failures stay uncertain. const uncertainOnExpiry = - this.#invokeTimeoutMs === 0 + isRead || this.#invokeTimeoutMs === 0 ? undefined : spokeReject( SpokeRejectCode.OUTCOME_UNCERTAIN, @@ -2216,17 +2221,22 @@ export class ConnectResponder { uncertainOnExpiry, ); } catch (error) { - // why: the service threw or rejected AFTER invocation, so the transport - // has no evidence that nothing committed (§14.3): answer uncertain — - // the same containment as a provider panic on the memory path — - // never a clean internal error. - result = spokeReject( - SpokeRejectCode.OUTCOME_UNCERTAIN, - `history service failed after invocation: ${ - error instanceof Error ? error.message : String(error) - }; the outcome is unknown — replay the same idempotency key`, - { retry_class: "uncertain", kind: "panic" }, - ); + // why: the service threw or rejected AFTER invocation. On any non-read + // op the transport has no evidence that nothing committed (§14.3), so + // it answers uncertain — the same containment as a provider panic on + // the memory path. The read op has no effect to be uncertain about, so + // it keeps the plain internal error. + const message = error instanceof Error ? error.message : String(error); + result = isRead + ? spokeReject( + SpokeRejectCode.INTERNAL_ERROR, + `history service failed after invocation: ${message}`, + ) + : spokeReject( + SpokeRejectCode.OUTCOME_UNCERTAIN, + `history service failed after invocation: ${message}; the outcome is unknown — replay the same idempotency key`, + { retry_class: "uncertain", kind: "panic" }, + ); } // note: a close during the bounded wait answers nothing afterwards. if (this.#stateInternal === "Closed") { diff --git a/packages/spoke-connect-ts/tests/remote/history-face.test.ts b/packages/spoke-connect-ts/tests/remote/history-face.test.ts index 611e5523..71484ef4 100644 --- a/packages/spoke-connect-ts/tests/remote/history-face.test.ts +++ b/packages/spoke-connect-ts/tests/remote/history-face.test.ts @@ -1230,6 +1230,115 @@ describe("history serving over the loopback responder", () => { } }); + it("a read serve budget expiring mid-invoke answers the plain serve timeout", async () => { + const { port, calls } = countingPort({ + get: async (_principal, _scope, _kind, id, revision) => { + calls.push(`get:${id}@${revision}`); + // note: the port outlives the responder budget on purpose — real + // delay, deterministic time cannot stand in for the serve budget. + await new Promise((resolve) => setTimeout(resolve, 200)); + return spokeOk(snapshot(id, revision)); + }, + }); + const service = new HistoryPortService(port, admission()); + const host = await dialHistoryHost({ + clientCapabilities: ["spoke-history"], + ports: { asHistory: () => service }, + // note: 60ms responder budget < 200ms port call < client budget. + hostInvokeTimeoutMs: 60, + }); + try { + const timedOut = await host.client.getHistorySnapshot( + PRINCIPAL_A, + SCOPE_A, + "knowledge_entry", + "ke_1", + 3, + ); + expect(timedOut.ok).toBe(false); + if (!timedOut.ok) { + // A read cannot have committed: plain internal error, no + // `retry_class` (exact details equality proves its absence). + expect(timedOut.code).toBe("INTERNAL_ERROR"); + expect(timedOut.details).toEqual({ kind: "timeout" }); + } + expect(calls).toEqual(["get:ke_1@3"]); + } finally { + host.close(); + } + }); + + it("a throwing history read answers the plain internal error with no details", async () => { + const service: RemoteHistoryService = { + invoke: async (_peerId, op) => { + if (op !== "history.revisions.get") { + throw new Error(`unexpected op ${op}`); + } + throw new Error("history get exploded"); + }, + }; + const host = await dialHistoryHost({ + clientCapabilities: ["spoke-history"], + ports: { asHistory: () => service }, + }); + try { + const failed = await host.client.getHistorySnapshot( + PRINCIPAL_A, + SCOPE_A, + "knowledge_entry", + "ke_1", + 3, + ); + expect(failed.ok).toBe(false); + if (!failed.ok) { + // A read cannot have committed: plain internal error, no `details` + // and therefore no `retry_class`. + expect(failed.code).toBe("INTERNAL_ERROR"); + expect(failed.message).toBe( + "history service failed after invocation: history get exploded", + ); + expect(failed.details).toBeUndefined(); + } + } finally { + host.close(); + } + }); + + it("a throwing history prune stays uncertain with the panic class", async () => { + const service: RemoteHistoryService = { + invoke: async (_peerId, op) => { + if (op !== "history.revisions.prune") { + throw new Error(`unexpected op ${op}`); + } + throw new Error("history prune exploded"); + }, + }; + const host = await dialHistoryHost({ + clientCapabilities: ["spoke-history"], + ports: { asHistory: () => service }, + }); + try { + const failed = await host.client.pruneHistory( + PRINCIPAL_A, + SCOPE_A, + "knowledge_entry", + "ke_1", + 2, + { idempotencyKey: "throwing-prune" }, + ); + expect(failed.ok).toBe(false); + if (!failed.ok) { + expect(failed.code).toBe("OUTCOME_UNCERTAIN"); + expect(failed.details).toEqual({ + retry_class: "uncertain", + kind: "panic", + }); + } + } finally { + host.close(); + } + }); + it("a serve budget expiring mid-invoke answers OUTCOME_UNCERTAIN and a same-key replay recovers", async () => { const { port, calls } = countingPort({ prune: async (_principal, _scope, _kind, id, keep) => {