feat(ActorResult): implement ActorResult and NodeUsage types; capture per-node token counts from LangChain responses #41
No reviewers
Labels
No labels
auto/blocked-by-deps
auto/ci-timeout
auto/claimed-implementer
auto/claimed-merge
auto/claimed-reviewer
auto/driver-down
auto/invariant-violation
auto/last-attempt-tier-0
auto/last-attempt-tier-1
auto/last-attempt-tier-2
auto/last-attempt-tier-min
Automation Tracking
auto/needs-conflict-resolution
auto/needs-implementer
auto/postmortem
auto/ready-to-merge
auto/restart-throttled
auto/revert
auto/sentinel
auto/stale-inactivity
auto/unstable
Blocked
Bounty
$100
Bounty
$1000
Bounty
$10000
Bounty
$20
Bounty
$2000
Bounty
$250
Bounty
$50
Bounty
$500
Bounty
$5000
Bounty
$750
MoSCoW
Could have
MoSCoW
Must have
MoSCoW
Should have
Needs Feedback
Points
1
Points
13
Points
2
Points
21
Points
3
Points
34
Points
5
Points
55
Points
8
Points
88
Priority
Backlog
Priority
CI Blocker
Priority
Critical
Priority
High
Priority
Low
Priority
Medium
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
State
Completed
State
Duplicate
State
In Progress
State
In Review
State
Paused
State
Unverified
State
Verified
State
Wont Do
Type
Automation
Type
Bug
Type
Discussion
Type
Documentation
Type
Epic
Type
Feature
Type
Legendary
Type
Refactor
Type
Support
Type
Task
Type
Testing
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Blocks
#14 feat(ActorResult): implement ActorResult and NodeUsage types; capture per-node token counts from LangChain responses
cleveragents/cleveractors-core
Reference
cleveragents/cleveractors-core!41
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "feature/actor-result"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Implements
cleveractors-coreissue #14 — the full AC1–AC7 acceptance criteria forActorResult,NodeUsage, and real LangChain token counting.Closes #14
Motivation
The CleverThis router consumes
Executor.execute()to run actors. Before this PR, the router receivedActorResultobjects whoseprompt_tokensandcompletion_tokensfields were estimated (via tiktoken or a 4-chars/token heuristic) rather than read from LangChain's actual response metadata. This made billing data inaccurate. The router also could not find the canonicalActorResult/NodeUsagetypes at the spec-mandated location (cleveractors.result).Changes
New module:
src/cleveractors/result.py(AC1)Defines
NodeUsageandActorResultdataclasses at the spec-mandated location. Also definesMAX_REASONABLE_TOKENS = 10_000_000as the single authoritative constant (previously duplicated in three modules).runtime.pynow imports and re-exports both types for backward compatibility.__init__.pyupdated to import fromresultinstead ofruntime. Uses lowercaselist[NodeUsage](PEP 585) throughout.nodesis a required positional field (no default) so the contract thatnodesis always non-empty is statically enforced.statefield usesdict[str, Any] | None(PEP 585, consistent with rest of codebase).__all__declaration added.LLMAgent— real token extraction + race-condition fix + billing integrity (AC2, AC3, M1, M2, m3)process_message()now:contextvars.ContextVar(last_token_usage_var) to store per-task token counts. Eachasyncio.Taskinherits a copy of the context, so parallel graph branches that share the sameLLMAgentinstance each see their own token counts — eliminating the race condition._last_token_usage = (0, 0)andlast_token_usage_var.set((0, 0))as the first statement inside thetry:block._captured_prompt,_captured_completion) immediately afterainvoke()succeeds, before the memory-update block. This marks the "ainvoke succeeded" boundary.ainvoke()step (e.g.update_memory()) raises an exception, theexcepthandlers check the sentinel variables. If_captured_prompt is not None,ainvoke()already succeeded and the LLM provider has already charged the user — the captured counts are preserved rather than zeroed. Only pre-ainvoke()failures (where no tokens were consumed) reset to(0, 0)... note::toprocess_message()documenting this billing integrity guarantee.Node._execute_agent()— race condition fix, agent-type-aware fallback (M1 cycle-9 fix)last_token_usage_varto(0, 0)at the start of thetry:block, before callingagent.process_message().LLMAgent, the ContextVar is authoritative —(0, 0)means zero tokens, not "unset". The fallback to_last_token_usageinstance attribute is never used forLLMAgentinstances, preventing the race where a sibling parallel branch overwrites the instance attribute. For non-LLMAgentagents (ToolAgent, ChainAgent, etc.), the ContextVar is always(0, 0)sinceprocess_message()does not touch it; these agents fall back to the instance attribute as before._node_token_usagetype annotation fromOptional[dict[str, Any]]todict[str, Any] | None(PEP 604, consistent with rest of codebase).runtime_dispatch.py— same agent-type-aware fallback in_execute_llm(M1 cycle-9 fix)_execute_llmfor consistency withNode._execute_agent()._nu_err→_node_usage_errin_execute_graph._normalize_node_id()helper and_GRAPH_PLACEHOLDER_REmodule-level regex.nu→node_usagein_execute_multi_actorfor readability.import reto the top-level import block.pure_graph.py— import organisationfrom cleveractors.result import MAX_REASONABLE_TOKENS as _MAX_REASONABLE_TOKENSto the top-level import block.features/mocks/actor_result_helpers.py— new mock helpers module (cycle-9 fix)_make_llm_actor_configand_make_mock_chat_modelfrom the step file intofeatures/mocks/actor_result_helpers.py(renamed tomake_llm_actor_configandmake_mock_chat_model), per project convention that mock factory functions belong infeatures/mocks/.BDD tests updated (M1, M2, m4, m5, m6, cycle-9 fixes)
t1 == (100, 50)andt2 == (200, 80)) instead of weak!= (0, 0)and!= each otherchecks. A buggy swapped-mapping implementation would now fail.except Exceptionin wrong-arity real-path test (cycle 9): Theartc_wrong_arity_real_path_testbranch no longer catches all exceptions and fabricates a fakeActorResult. Ifexecutor.execute()raises unexpectedly, the test now fails loudly.step_artc_graph_executor_wrong_arity_tuple(cycle 9): This ~44-line step was never referenced by any scenario in the feature file.LLMAgentinstance is called concurrently viaasyncio.gather()with two different mockedusage_metadataresponses; each task asserts itslast_token_usage_var.get()reflects its own call's counts.LLMAgentwithmemory_enabled=Truesucceeds atainvoke()but fails atupdate_memory(); asserts_last_token_usage == (42, 17)after the exception (previously incorrectly asserted(0, 0)). This verifies that billing data is not lost when memory persistence fails._safe_node_token_int(20_000_000)and_safe_token_int(20_000_000)both return20_000_000unchanged.Node._execute_agent()code path viaAgentFactory.create_agentmock.CHANGELOG.md — stale reference removed
_usage_logreference from the "Mutable state hygiene" entry (this field never existed in this PR's scope). The entry now accurately describes the actual new mechanism:_last_token_usageandlast_token_usage_varare reset at the start of everyprocess_message()call;PureLangGraph._node_usagesis reset at the start of everyexecute()call; post-ainvoke()exceptions preserve captured token counts for billing integrity.Architecture Note
AC3 says "
process_message()returns token counts alongside the response string." Changing theAgentabstract base class return type fromstrtotuple[str, int, int]would require updating all four concrete agent implementations plus every mock in the test suite. Instead, thecontextvars.ContextVarside-channel satisfies the spirit of AC3 — token counts are available alongside the response, per-task and race-free — without breaking the existing Agent contract.Billing Integrity Design
When
ainvoke()succeeds but a subsequent step (e.g.update_memory()) raises an exception:ainvoke().excepthandlers check sentinel variables (_captured_prompt,_captured_completion) set immediately afterainvoke()succeeds._last_token_usageandlast_token_usage_varso the router receives accurate billing data.ainvoke()failures (sentinels stillNone) reset counts to(0, 0), because in those cases no tokens were consumed.Quality Gates
nox -e lintnox -e typechecknox -e unit_testsnox -e integration_testsnox -e coverage_reportADR References
Deferred Items
_safe_int()/_safe_token_int()consolidation (N1): Both helpers implement the same coercion logic. Moving to a shared module is a refactor deferred to a follow-up ticket.NodeUsageTuplelocation (issue #13): Moving the type alias tocleveractors.resultis a minor organizational improvement deferred to a follow-up.Literal[...]annotation duplicating_CAUSE_*constants: Python'sLiteraltype does not support referencing constant names directly, so the string values must be duplicated. This is a known limitation of the language and is accepted as-is.Node.__init__setsself.logger = logging.getLogger(__name__)which produces the same object as the module-level_logger. Consolidating to use_loggerdirectly inNodeis a pre-existing nit deferred to a follow-up._read_last_token_usage(agent)helper is a refactor deferred to a follow-up._execute_llm/_execute_toolcompute totals directly): Inconsistency withsum()pattern used in_execute_graph/_execute_multi_actoris deferred to a follow-up.25e6cce9108a09b964128a09b96412ad3186a07ead3186a07ee969851786e969851786498f0f87ae498f0f87ae7f0e4597177f0e4597176d1eca444d6d1eca444d40c102574d40c102574db21a41e16ab21a41e16a9491b69f109491b69f10ea355c6433ea355c6433ab8b1451f0ab8b1451f07068d5d6647068d5d664403d3e683a403d3e683a7d218338277d218338270a120b2ec20a120b2ec2e778443aade778443aad16f8d4b94516f8d4b94554c15c177854c15c1778b488e10bdfb488e10bdf2657f8c3112657f8c3111a6648d7631a6648d763dd17cd6467dd17cd6467e772d04193e772d04193c9dbfa6517c9dbfa65172664ebfd75Review: Issue Compliance & Regression Check
Reviewed against two questions: (1) does the code implement what issue #14 requires, and (2) does it break anything?
1. Issue #14 acceptance criteria — all met ✅
result.pywithNodeUsage/ActorResultstatepreserved per ADR-2026;__all__declaredusage_metadata→response_metadatafallback → warn+0)_safe_int()handles booleans, negatives, overflow, and implausible valuescontextvars.ContextVar+_last_token_usageside-channel; architecture note in PR is soundPureLangGraphcollects per-node(node_id, provider, model, prompt, completion)Node._execute_agent()writes_node_token_usageinto state;_execute_from_node()pops it and accumulates intoself._node_usagesExecutor.execute()aggregates intoActorResultwith real counts_execute_llm,_execute_graph,_execute_tool,_execute_multi_actor) rebuilt; estimation helpers deletedprompt_tokens == sum(n.prompt_tokens for n in nodes)_execute_graph; recomputed after node-id prefixing in_execute_multi_actorActorResult/NodeUsageexported from__init__.pyand__all____init__.pyimports directly fromcleveractors.result;result.pyhas__all__All subtasks from the issue are checked off, including deletion of
runtime_tokens.pyand_estimate_tokens().2. Regressions — none found ✅
Intentional breaking changes (all call sites updated, tests confirm):
ActorResult.nodesis now a required field (no default). Correct per spec; the bot'sfield(default_factory=list)was an earlier deviation. Every creation site inruntime_dispatch.pyprovidesnodes.Executor._usage_logremoved. All four internal references cleaned up.runtime_tokens.pydeleted. Its only caller (runtime_dispatch.py) is updated.Return-type propagation — handled everywhere:
PureLangGraph.execute()now returns a 3-tuple. All four call sites updated:_execute_graph,PureLangGraph.process_message(), and both locations inapplication.py.process_message()also fixes a pre-existing bug where it was returning a tuple instead of astr.Backward compatibility preserved:
from cleveractors.runtime import ActorResult,from cleveractors.runtime_types import ActorResult, andfrom cleveractors import ActorResult, NodeUsageall continue to work via shim re-exports.Concurrency correctness:
The
contextvars.ContextVarpattern is correct for asyncio — eachTaskinherits a copy of the context at creation time, making parallel branches that share the sameLLMAgentinstance race-free. The billing-integrity sentinels (_captured_prompt is not None) correctly distinguish pre-ainvoke()failures from post-ainvoke()failures. Token counts are read beforecleanup()runs in thefinallyblock.Verdict: safe to merge ✅
Quality gates (lint, typecheck, 2298/2298 unit tests, integration tests, 97.1% coverage) all green. The deferred items (N1–N4) are code-quality nits with no correctness impact.