Skip to content

fix(activities): record a user-cancelled execution as CANCELLED, not FAILED (#1332) - #1361

Merged
vybe merged 9 commits into
devfrom
AndriiPasternak31/issue-1332
Jun 28, 2026
Merged

vybe merged 9 commits into
devfrom
AndriiPasternak31/issue-1332

Conversation

@AndriiPasternak31

Copy link
Copy Markdown
Contributor

Summary

Fixes #1332 — a user-cancelled execution's dispatch activity was recorded as ActivityState.FAILED, so operator cancels were conflated with genuine agent failures across every activity-derived view (collaboration timeline, replay, Overview "needs-attention", activity-based health). The execution row was already correctly CANCELLED (#679); only the activity layer collapsed the cancel into a failure.

This adds a first-class CANCELLED activity terminal, routes every close-site through one shared mapping helper, handles all three ways a cancel reaches the activity layer, and renders the cancelled state distinctly in the timeline.

Observability-only — no money/data-correctness bug. Execution-row analytics (terminal-based success rate over schedule_executions.status) already excluded CANCELLED correctly and are untouched.

The fix

Model layer (models.py, db/schema.py)

  • ActivityState.CANCELLED = "cancelled".
  • activity_state_for_terminal(status) — the single mapping every close-site shares: SUCCESS → COMPLETED, CANCELLED → CANCELLED, else → FAILED. Accepts a TaskExecutionStatus or its bare string (str-backed enum); the explicit else keeps a future status deterministic.
  • No DB migration: activity_state is a TEXT column with no CHECK; the enum is app-level only.

Three cancel paths, all handled

Path Where Behaviour
A — agent self-reports a CANCELLED terminal task_execution_service.apply_result Both close-sites (won-CAS failure branch + SUCCESS-lost-CAS reconcile) derive state from activity_state_for_terminal. A late SUCCESS only ever loses the CAS to a CANCELLED row, so it reads "superseded by cancelled".
B — operator terminate routers/chat.py terminate_agent_execution Writes the CANCELLED row first and never reaches apply_result, so the dispatch activity used to sit started until the ~30-min stale reaper flipped it to FAILED. Now explicitly closes the open dispatch activity CANCELLED (get_open_activity_id_for_execution + complete_activity), best-effort. CAS-gated: if the CANCELLED row-write loses the CAS (row already terminal via a concurrent path), the activity closes in the row's real state so it never disagrees with the row.
C — sync-chat exception handlers _run_chat_and_finalize (budget-exhausted 503, httpx.HTTPError) Read the row state before closing the chat/collab activities, so a cancel that raced a transport/budget error closes CANCELLED and the handler's error isn't stamped over the cancel. A still-RUNNING/missing row still maps to FAILED (genuine-failure guard); the FAILED row-write is still skipped over a CANCELLED row.

Collaboration / self-task closes (_complete_collaboration_activity, _finalize_self_task, execute_parallel_task) also move off the hard-coded COMPLETED if SUCCESS else FAILED ternary onto the helper; the self-task WS broadcast mirrors the activity DB state so event and row never disagree.

A cancel is not an AUTH failure → no dispatch-breaker outcome is recorded.

Frontend (ReplayTimeline.vue)

  • A cancelled event carries error="Execution terminated by user", which made hasError truthy and rendered the bar red. Now status === 'cancelled' is detected, excluded from hasError, and given a distinct slate #94a3b8 bar via a new getBarColor/isCancelled branch + (Cancelled) tooltip.
  • isCancelled is carried onto both the intermediate act object and the FINAL rendered bar — getBarColor/getBarTooltip read the rendered bar, so dropping it there had left the slate color + tooltip dead.

Acceptance criteria

  • A cancelled execution's dispatch activity is recorded as cancelled (not FAILED).
  • Frontend renders the cancelled state distinctly from failed (slate bar + (Cancelled) tooltip).
  • No activity-derived health/needs-attention surface counts an operator cancel as a failure.
  • Genuine failures still record ActivityState.FAILED (regression guard — Path C RUNNING-row test).
  • Unit test covering the apply_result CANCELLED → activity-state path (plus Paths B and C).

Testing

  • New tests/unit/test_1332_cancelled_activity_state.py — enum value + activity_state_for_terminal (incl. bare-string), Path B terminate handler (terminated→CANCELLED, already_finished→no-op, no-open-activity→no-op, close-raises→swallowed, CAS-lost→close in row's real state), collaboration/self-task closes.
  • New Path-C cases in test_chat_admission.py — HTTP-error & budget-exhausted on an already-CANCELLED row close CANCELLED (error dropped, no FAILED write) + RUNNING-row regression guard (still FAILED, one FAILED write).
  • New e2e src/frontend/e2e/timeline-cancelled-bar.spec.js — timeline renders a cancelled execution slate, not red; authenticated agent-existence probe so the skip is honest in CI.
  • Regression flips: test_679_backend_cancel.py, test_1083_apply_result.py, test_activities.py.

Docs

architecture.md, feature-flows.md (Recent Updates row), activity-stream.md, activity-stream-collaboration-tracking.md, dashboard-timeline-view.md, execution-termination.md, task-execution-service.md.

Security

/cso --diff (daily 8/10 gate) — no findings. Report committed under docs/security-reports/cso-diff-2026-06-26.md. Terminate endpoint auth unchanged; new DB read is pre-existing parameterized SQLAlchemy-core; cancelled tooltip renders auto-escaped through Vue (no v-html).

Notes

  • P3 · type-bug · theme-reliability · complexity-medium.
  • Base branch dev per the team feature-PR workflow.
  • Opened as draft — pending /verify-local and team review (SOC 2 separation of duties: someone else validates).

🤖 Generated with Claude Code

AndriiPasternak31 and others added 7 commits June 26, 2026 23:45
…al helper

Introduce a CANCELLED activity terminal, distinct from FAILED, plus a single
mapping helper every activity close-site can share:

- ActivityState gains CANCELLED = "cancelled". A user-initiated cancel must
  read as a distinct, non-failure terminal so activity-derived views
  (collaboration timeline, replay, needs-attention) don't collapse it into
  FAILED.
- activity_state_for_terminal(status): SUCCESS -> COMPLETED,
  CANCELLED -> CANCELLED, everything else -> FAILED. Accepts a
  TaskExecutionStatus or its bare string value (str-backed enum); the explicit
  else keeps a future status deterministic.

No DB migration: activity_state is a TEXT column with no CHECK constraint —
the enum is enforced at the application layer only. schema.py / the
ActivityCompleteRequest docstring updated to list the new value.

Refs #1332

Co-Authored-By: Claude Opus 4.8 <[email protected]>
apply_result previously closed the dispatch activity as ActivityState.FAILED
for any non-SUCCESS terminal, so a cancelled execution's own activity was
recorded as a failure even though its schedule_executions row was correctly
CANCELLED.

Both close-sites now derive the activity state from the persisted terminal via
activity_state_for_terminal():

- Won-CAS failure branch (Path A — agent self-reports a CANCELLED terminal):
  maps envelope.status, so a CANCELLED envelope closes the activity CANCELLED.
- SUCCESS-lost-CAS reconcile branch: a late SUCCESS only ever loses the CAS to
  a CANCELLED row (the schedules.py SUCCESS guard is `status != CANCELLED`), so
  the superseded activity now closes CANCELLED ("superseded by cancelled")
  instead of FAILED.

A cancel is still not an AUTH failure, so no breaker outcome is recorded.

Refs #1332

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Thread the cancelled terminal through every activity close-site in the chat
router so an operator cancel never reads as a failure:

- Collaboration / self-task closes (_complete_collaboration_activity,
  _finalize_self_task, execute_parallel_task) replace the hard-coded
  `COMPLETED if SUCCESS else FAILED` ternary with activity_state_for_terminal().
  The self-task WS broadcast now mirrors the activity DB state (cancelled stays
  cancelled) so the event and the persisted row never disagree.

- Path B (operator terminate, terminate_agent_execution): this path writes the
  CANCELLED row first and never reaches apply_result (the async callback
  short-circuits on the authoritative terminal; a sync apply_result loses the
  CAS), so the open dispatch activity used to stay `started` until the ~30-min
  stale-activity reaper flipped it to FAILED. It now explicitly closes the open
  dispatch activity as CANCELLED (get_open_activity_id_for_execution +
  complete_activity), best-effort like _close_stale_slot_activity. The close is
  CAS-gated: if the CANCELLED row-write loses the CAS (row already terminal via
  a concurrent path), the activity closes in the row's REAL state so it never
  disagrees with the row.

- Path C (synchronous-chat exception handlers in _run_chat_and_finalize:
  budget-exhausted 503, httpx.HTTPError): read the row state BEFORE closing the
  chat/collab activities, so a cancel that raced a transport/budget error
  closes those activities CANCELLED and the handler's error isn't stamped over
  the cancel. A still-RUNNING/missing row still maps to FAILED (genuine-failure
  guard); the FAILED row-write is still skipped over a CANCELLED row.

Refs #1332

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A cancelled execution carries error="Execution terminated by user", which made
the timeline bar's hasError truthy and rendered it the same red as a genuine
failure. ReplayTimeline now treats cancelled as its own state:

- Detect event.status === 'cancelled' and exclude it from hasError.
- Carry isCancelled onto BOTH the intermediate `act` object AND the FINAL
  rendered `bar` (getBarColor/getBarTooltip read the rendered bar, not `act` —
  dropping it there had left the slate color + tooltip dead).
- getBarColor returns slate #94a3b8 for cancelled, checked before the
  hasError/in-progress/trigger branches; getBarTooltip shows "(Cancelled)".

Refs #1332

Co-Authored-By: Claude Opus 4.8 <[email protected]>
New coverage:
- tests/unit/test_1332_cancelled_activity_state.py — the CANCELLED enum value +
  activity_state_for_terminal mapping (incl. bare-string input), Path B
  terminate handler (terminated -> close CANCELLED, already_finished -> no-op,
  no-open-activity -> no-op, close-raises -> swallowed, CAS-lost -> close in the
  row's REAL state), and the collaboration/self-task closes.
- test_chat_admission.py — Path C cancel-aware cases: HTTP error and
  budget-exhausted on an already-CANCELLED row close the chat activity CANCELLED
  (error dropped, no FAILED row-write), plus a regression guard that a genuine
  HTTP failure on a still-RUNNING row still closes FAILED with error text + one
  FAILED write.
- e2e/timeline-cancelled-bar.spec.js — the Dashboard timeline renders a
  cancelled execution as a slate bar (not red) with a "(Cancelled)" tooltip;
  authenticated agent-existence probe so the skip is honest in CI.

Regression flips for the new terminal label:
- test_679_backend_cancel.py / test_1083_apply_result.py — apply_result now
  closes a cancel CANCELLED (not FAILED); SUCCESS-lost-to-cancel reads
  "superseded by cancelled".
- test_activities.py — accept 'cancelled' as a valid activity_state.
- registry.json — register the new unit test.

Refs #1332

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- architecture.md: agent_activities.activity_state now lists `cancelled`;
  Collaboration Dashboard detection note records a cancel as distinct from
  failed.
- feature-flows.md: Recent Updates row for #1332 (Paths A/B/C + frontend +
  no-migration note).
- activity-stream.md / activity-stream-collaboration-tracking.md: the
  activity_state_for_terminal helper drives every close-site; collaboration
  closes map a cancel to CANCELLED.
- dashboard-timeline-view.md: slate Cancelled color row + getBarColor branch.
- execution-termination.md: step 4b — Path B closes the dispatch activity
  CANCELLED, best-effort + CAS-gated.
- task-execution-service.md: terminal-applier close row in the activity table.

Refs #1332

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Daily-gate (8/10) diff scan of the branch vs origin/dev. Verdict: no findings —
a tightly-scoped observability change with no new endpoints, inputs, auth,
dependency/CI/Docker changes, or user-content rendering. Terminate endpoint
auth unchanged; new DB read is pre-existing parameterized SQLAlchemy-core; the
cancelled tooltip renders auto-escaped through Vue (no v-html). Point-in-time
report under docs/security-reports/ (out of scope of the enterprise-docs-guard).

Refs #1332

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@AndriiPasternak31
AndriiPasternak31 marked this pull request as ready for review June 26, 2026 22:50
@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

…n class (#1332)

The seed-67890 regression-diff failure was test isolation, not a product
defect. test_904_agent_call_limiter.py::test_default_timeout_is_one_hour calls
importlib.reload(services.agent_call_limiter), rebinding
BackendAgentCallBudgetExhausted to a new class object. routers/chat.py bound the
original class at import (except BackendAgentCallBudgetExhausted), so a fresh
`from services.agent_call_limiter import ...` in this test yielded the
post-reload class under orderings where test_904 ran first — the simulated
exception then escaped the handler uncaught and pytest.raises(HTTPException)
failed.

Raise _CHAT.BackendAgentCallBudgetExhausted (the exact class the handler
catches) so the test is order-independent. No production code changes.

Verified: full unit suite under --randomly-seed=67890 drops from 7 to 6
failures (the remaining 6 are the pre-existing test_1115 dev bug, present on
dev/base), i.e. zero new HEAD failures.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@AndriiPasternak31 AndriiPasternak31 self-assigned this Jun 27, 2026
@AndriiPasternak31
AndriiPasternak31 requested review from dolho and vybe and removed request for vybe June 27, 2026 19:04
Resolve docs/memory/feature-flows.md Recent-Updates index conflict:
union of both row-sets, newest-first (dev's 06-28/06-27 rows above the
#1332 06-26 row). Code files auto-merged cleanly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validated via /validate-pr (see report below).

  • Substance: clean. activity_state_for_terminal is a single shared mapping with an explicit else → FAILED; TaskExecutionStatus(str, Enum) confirms the documented bare-string comparison is valid. All three cancel paths (apply_result / operator terminate / sync-chat exception handlers) read row state before closing and CAS-guard the FAILED write so a cancel is never stamped over.
  • Security: /cso --diff committed, no findings; my diff scan found no secrets/keys/PII; tooltip auto-escaped via Vue (no v-html).
  • Tests: unit (Paths A/B/C incl. RUNNING-row genuine-failure regression guard) + e2e spec + regression flips. Issue #1332 linked with closing keyword (auto-promotes to status-in-dev).
  • Merge conflict in docs/memory/feature-flows.md (Recent-Updates index) resolved by merging dev into the branch; code auto-merged cleanly.

Note: frontend-e2e is skipped (no ui label) so the new timeline-cancelled-bar spec doesn't run in CI — non-blocking given unit coverage.

@vybe
vybe enabled auto-merge (squash) June 28, 2026 12:25
@vybe
vybe merged commit 69a3cda into dev Jun 28, 2026
19 checks passed
@vybe
vybe deleted the AndriiPasternak31/issue-1332 branch June 28, 2026 12:30
vybe pushed a commit that referenced this pull request Nov 23, 2026
…al routes (Abilityai/trinity-enterprise#1358) (#4744)

Moves src/backend/enterprise from 552bd6a to 636c6d5, enterprise main tip.
Carries #1361 (assistant credential routes) and #1344 (one-line doc).

Refs Abilityai/trinity-enterprise#1358

Co-authored-by: Trinity Agent (trinity) <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants