Skip to content
Merged
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
71 changes: 45 additions & 26 deletions crates/spoke-connect/src/remote/responder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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()));
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Comment thread
auto-wood marked this conversation as resolved.
Resolved
let bounded = if zero_budget {
None
} else {
Expand All @@ -2281,19 +2289,30 @@ 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,
}
};
if self.state() == ConnectResponderState::Closed {
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)
Expand Down
119 changes: 115 additions & 4 deletions crates/spoke-connect/tests/remote_loopback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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<Value> {
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
Expand Down Expand Up @@ -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"
Expand All @@ -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<dyn RemoteServePorts + Send + Sync> = 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<dyn RemoteServePorts + Send + Sync> = 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]
Expand Down
7 changes: 5 additions & 2 deletions docs/reference/history.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 5 additions & 2 deletions docs/zh/reference/history.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 成员;其余代码保持既有含义。

Expand Down
Loading
Loading