Skip to content

Commit c977cfd

Browse files
committed
fix(chat): retire stopped quota failures from pending readback
Signed-off-by: Yuchao Wang <stevenkid404@gmail.com>
1 parent da4510a commit c977cfd

6 files changed

Lines changed: 92 additions & 14 deletions

File tree

‎docs/reference/protocols/manager-evidence-and-continuity-v0.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,18 @@ readback remain in force, preserving the failed Turn and its original notice.
450450
仍保留待核对,不能走此路径重放。退避、三次上限、稳定接续身份、失败历史和逐次
451451
原受众送达读回均保持原约束。
452452

453+
The existing pending count retains delivered quota failures while work remains
454+
outstanding. A later same-source `/stop` or `/new`, or closure of the original
455+
Session, retires that backlog from the read-only count without deleting the
456+
failed Turn or notice. Temporary binding/provider unavailability, backoff and
457+
retry exhaustion are not retirement evidence. Health reads neither admit
458+
recovery nor contact a provider.
459+
460+
既有待处理数量保留已送达失败通知、仍未结束的额度失败工作。后续同来源 `/stop`、
461+
`/new` 或原 Session 关闭后,只读计数不再包含该积压;失败 Turn 和通知仍保留。
462+
临时绑定/provider 不可用、退避和重试耗尽不代表退休。健康读取不准入恢复,
463+
也不访问 provider。
464+
453465
Default manager duties allow authorized reads and summaries; reminders use an
454466
existing authorized destination/subscription. Goal changes, steering,
455467
cross-Goal dispatch, pause/resume, publishing, and trading keep their existing

‎loopx/capabilities/native_chat/external_conversations.py‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -75,14 +75,6 @@ def _context_recovery_plan(self, row: dict[str, Any], *,
7575
or reservation.get("read_only_review") or reservation.get("work_attempt"))
7676
and reservation.get("failed_turn_id") == row["turn_id"] else None)
7777
events = store.events_after(session["session_id"], turn["turn_id"], None)
78-
# A later source control also retires an unexecuted failed request.
79-
# The source fence makes this inventory consistent with admission.
80-
stop = any(event.get("kind") in {"turn.interrupt_requested", "turn.interrupted"} for event in events)
81-
if turn.get("status") in {"failed", "completed"}:
82-
stop = stop or any(item.get("binding_id") == row["binding_id"]
83-
and item.get("source") == row["source"] and item.get("command") in {"stop", "new"}
84-
and datetime.fromisoformat(item["created_at"]) >= datetime.fromisoformat(row["created_at"])
85-
for item in self.pending())
8678
return effect_runtime_result("collaboration.conversation.request", {
8779
"request": {key: value for key, value in row.items() if key != "attachments"},
8880
"current_session": session, "binding": selected_binding,
@@ -91,10 +83,35 @@ def _context_recovery_plan(self, row: dict[str, Any], *,
9183
"admitted_turn": admitted,
9284
"attachments_present": bool(row.get("attachments")),
9385
"steering_observed": any(event.get("kind") == "turn.steered" for event in events),
94-
"stop_observed": stop,
86+
"stop_observed": self._source_stop_observed(row, turn, events),
9587
"native_observation": observation, "source_verified": source_verified},
9688
})
9789

90+
def _source_stop_observed(self, row: dict[str, Any], turn: dict[str, Any],
91+
events: list[dict[str, Any]]) -> bool:
92+
"""Read the same durable source controls for recovery and display."""
93+
return (any(event.get("kind") in {"turn.interrupt_requested", "turn.interrupted"} for event in events)
94+
or (turn.get("status") in {"failed", "completed"} and any(
95+
item.get("binding_id") == row["binding_id"] and item.get("source") == row["source"]
96+
and item.get("command") in {"stop", "new"}
97+
and datetime.fromisoformat(item["created_at"]) >= datetime.fromisoformat(row["created_at"])
98+
for item in self.pending())))
99+
100+
def quota_backlog_pending(self, row: dict[str, Any]) -> bool:
101+
"""Project existing work without resolving providers or admitting recovery."""
102+
from ...control_plane.effect_runtime import effect_runtime_result
103+
104+
store = self.controller.store
105+
session = store.load_session(row["session_id"])
106+
turn = store.load_turn(row["session_id"], row["turn_id"])
107+
events = store.events_after(row["session_id"], row["turn_id"], None) if turn else []
108+
return effect_runtime_result("collaboration.conversation.request", {
109+
"request": {key: value for key, value in row.items() if key != "attachments"},
110+
"current_session": session,
111+
"pending_observation": {"turn": turn,
112+
"stop_observed": self._source_stop_observed(row, turn, events) if turn else False},
113+
}).get("pending") is True
114+
98115
def context_recovery_candidate(self, request_ref: str) -> bool:
99116
"""Discovery only; every authority and native fact is re-read at admission."""
100117
try:

‎loopx/control_plane/collaboration/conversation_binding.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,18 @@ export function planBoundConversationRequest(params: JsonObject): JsonObject {
437437
throw new EffectRuntimeRequestError("unsupported external conversation command");
438438
}
439439
const current = params.current_session === null ? null : requireJsonObject(params.current_session, "current Session");
440+
if (params.pending_observation !== undefined) {
441+
const observation = requireJsonObject(params.pending_observation, "pending work observation");
442+
const turn = observation.turn == null ? null : requireJsonObject(observation.turn, "observed Turn");
443+
// Pending work is not current retry eligibility: backoff, disabled bindings,
444+
// exhausted attempts and unavailable providers do not retire the request.
445+
// Only explicit lifecycle evidence removes a delivered quota failure.
446+
return {pending: row.command === null && row.status === "accepted"
447+
&& turn?.session_id === row.session_id && turn?.turn_id === row.turn_id
448+
&& turn?.status === "failed" && turn.error_code === "usage_limit_exceeded"
449+
&& !(current?.session_id === row.session_id && current?.status === "closed")
450+
&& observation.stop_observed !== true};
451+
}
440452
if (params.context_recovery !== undefined) {
441453
return planContextRecovery(params, row, current);
442454
}

‎loopx/extensions/lark/private_conversations.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,9 +235,7 @@ def health(self) -> dict[str, dict[str, int]]:
235235
if (native.get("status") == "accepted" and native.get("command") is None
236236
and all(native.get(key) == row.get(key) for key in
237237
("binding_id", "source", "session_id", "turn_id"))):
238-
turn = self.core.controller.store.load_turn(row["session_id"], row["turn_id"])
239-
pending = bool(turn and turn.get("status") == "failed"
240-
and turn.get("error_code") == "usage_limit_exceeded")
238+
pending = self.core.quota_backlog_pending(native)
241239
if pending:
242240
entry["pending_count"] += 1
243241
entry["recovery_count"] += int(any(phase.get("started") and not phase.get("verified")

‎tests/control_plane_ts/conversation_binding.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,3 +702,31 @@ test("local input cannot impersonate a group participant or inherit its workspac
702702
assert.equal(resolveConversationScope({goal_id: null, channel_id: selected.channel_id,
703703
project_context: selected.context, origin: "web"}).kind, "unavailable");
704704
});
705+
706+
test("quota backlog projection retires explicit lifecycle stops, not unavailable recovery", () => {
707+
const original = {request_ref: "f".repeat(24), command: null, status: "accepted",
708+
session_id: "original", turn_id: "failed"};
709+
const turn = {session_id: "original", turn_id: "failed", status: "failed", error_code: "usage_limit_exceeded"};
710+
const packet = {request: original, current_session: {session_id: "original", status: "ready"},
711+
pending_observation: {turn, stop_observed: false}};
712+
assert.equal(planBoundConversationRequest(packet).pending, true);
713+
// No binding/provider/native allowance input is necessary for this read.
714+
assert.equal(planBoundConversationRequest({...packet, request: {...original,
715+
context_recovery: {quota_attempt: 3, not_before: "2099-01-01T00:00:00Z"}}}).pending, true);
716+
assert.equal(planBoundConversationRequest({...packet, current_session: null}).pending, true,
717+
"missing session evidence must not silently retire known quota work");
718+
assert.equal(planBoundConversationRequest({...packet,
719+
current_session: {session_id: "foreign", status: "closed"}}).pending, true);
720+
assert.equal(planBoundConversationRequest({...packet,
721+
current_session: {...packet.current_session, status: "closed"}}).pending, false);
722+
assert.equal(planBoundConversationRequest({...packet,
723+
pending_observation: {...packet.pending_observation, stop_observed: true}}).pending, false);
724+
for (const changed of [null, {...turn, error_code: "policy"}, {...turn, status: "completed"},
725+
{...turn, session_id: "foreign"}, {...turn, turn_id: "foreign"}]) {
726+
assert.equal(planBoundConversationRequest({...packet,
727+
pending_observation: {turn: changed, stop_observed: false}}).pending, false);
728+
}
729+
for (const changed of [{...original, command: "stop"}, {...original, status: "rejected"}]) {
730+
assert.equal(planBoundConversationRequest({...packet, request: changed}).pending, false);
731+
}
732+
});

‎tests/test_chat_conversation_bindings.py‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
from loopx.extensions.lark.conversation_identity import identity_ref
1313

1414

15-
def test_quota_backlog_observes_a_later_source_stop_before_new_admission(ordinary, monkeypatch): # noqa: F811
15+
@pytest.mark.parametrize("command", ["stop", "new"])
16+
def test_quota_backlog_observes_a_later_source_stop_before_new_admission(ordinary, monkeypatch, command): # noqa: F811
1617
from datetime import datetime, timedelta, timezone
1718
from loopx.capabilities.native_chat import external_conversations
1819
from test_lark_private_conversations import connect
@@ -38,7 +39,10 @@ def now(cls, tz=None):
3839
assert transport.core._context_recovery_plan(original, discovery_only=True)["recovery_candidate"]
3940
transport.admit("steward-app", provider.event("steward-app", "unrelated-stop", "/stop"))
4041
assert transport.core._context_recovery_plan(original, discovery_only=True)["recovery_candidate"]
41-
transport.admit("notes-app", provider.event("notes-app", "later-stop", "/stop"))
42+
assert transport.health()[row["binding_id"]]["pending_count"] == 1
43+
transport.admit("notes-app", provider.event("notes-app", "later-stop", f"/{command}"))
44+
transport.reconcile()
45+
assert transport.health()[row["binding_id"]]["pending_count"] == 0
4246
calls = ordinary[4].read_bytes()
4347
assert not transport.core._context_recovery_plan(original, discovery_only=True)["recovery_candidate"]
4448
assert ordinary[4].read_bytes() == calls
@@ -47,6 +51,13 @@ def now(cls, tz=None):
4751
newer = next(x for x in transport.core.pending() if x.get("message") == "A new independent request")
4852
completed = runtime.wait_for_turn(session_id=newer["session_id"], turn_id=newer["turn_id"], timeout_sec=10)
4953
assert completed["status"] == "completed"
54+
transport.reconcile()
55+
from loopx.extensions.lark.private_conversations import LarkPrivateConversations
56+
restarted = LarkPrivateConversations(controller=runtime, runtime_root=transport.runtime_root,
57+
runner=provider, cli_bin="lark-cli")
58+
before = ordinary[4].read_bytes(), list(provider.calls)
59+
assert restarted.health()[row["binding_id"]]["pending_count"] == 0
60+
assert (ordinary[4].read_bytes(), provider.calls) == before
5061
assert store.load_turn(row["session_id"], row["turn_id"]) == failed
5162
finally:
5263
runtime.close()

0 commit comments

Comments
 (0)