feat(ActorResult): implement ActorResult and NodeUsage types; capture per-node token counts from LangChain responses #41
Merged
hurui200320
merged 1 commits from 2026-06-11 03:25:35 +00:00
feature/actor-result into master
No Reviewers
Labels
Clear 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
Needs Feedback
Signed-off: Owner
Signed-off: Scrum Master
Signed-off: Tech Lead
Spike
PR blocked by an open issue dependency. Operator must close the dep (or remove the dependency link) before the merge driver can act. Auto-cleared by merge_drive when no open deps remain.
Most recent merge cycle hit CI timeout. Driver excludes this PR while last merge_cycle row is < 30 min old; label persists thereafter as visible history.
Currently being processed by an implementer worker.
Currently being processed by the merge driver.
Currently being processed by a reviewer worker.
Merge driver heartbeat stale; pipeline halted. Closed automatically on next clean tick.
Detected master commit violating the strict merge invariant. Tracked as an issue (not a PR label); kept here for label completeness.
In-cycle escalation: most recent attempt ran at the Tier 0 slot (`tier-0`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 1 slot (`tier-1`). Slot's model defined in .opencode/models/tiers.yaml.
In-cycle escalation: most recent attempt ran at the Tier 2 slot (`tier-2`). Slot's model defined in .opencode/models/tiers.yaml. Gated behind IMPLEMENTER_ESCALATION_TIER2_ENABLED.
In-cycle escalation: most recent attempt ran at the Tier -1 slot (`tier-min`). Slot's model defined in .opencode/models/tiers.yaml. Suffix is ``-min`` (not ``--1``) so the Forgejo UI reads naturally.
Tracking issues used by the AI Automation system for agents to communicate and report.
Rebase conflict needs LLM conflict-resolver.
Failing CI needs implementer attention.
Documenting a driver incident or rollback.
Reviewer has APPROVED this PR and no later REQUEST_CHANGES is outstanding. The merge driver requires this label to even consider a PR for merging. Set by the reviewer worker on APPROVE; cleared on REQUEST_CHANGES.
Train repeatedly lost master-tempo races. Driver excludes via merge_cycle until cooldown elapses; label persists as visible history.
Revert PR backing out an invariant violation. Fast-tracked through the merge driver.
Sentinel PR duplicated from upstream into a personal fork by tools/duplicate_prs_to_fork.py for pipeline testing. Lives only in the fork; the canonical pipeline never sees it.
No implementer activity for N days. Flagged for human review. Auto-cleared on next push to head branch.
Repeatedly fails on current master (>= 3 ci-fail-on-rebased-sha releases in 12 h). Excluded from driver until human triage.
A ticket in a blocked state and unable to complete until some other task is completed first.
Bounty
$100
A bounty of $100 for any open-source contributor who provides a MR that solves this issue
Bounty
$1000
A bounty of $1000 for any open-source contributor who provides a MR that solves this issue
Bounty
$10000
A bounty of $10000 for any open-source contributor who provides a MR that solves this issue
Bounty
$20
A bounty of $20 for any open-source contributor who provides a MR that solves this issue
Bounty
$2000
A bounty of $2000 for any open-source contributor who provides a MR that solves this issue
Bounty
$250
A bounty of $250 for any open-source contributor who provides a MR that solves this issue
Bounty
$50
A bounty of $50 for any open-source contributor who provides a MR that solves this issue
Bounty
$500
A bounty of $500 for any open-source contributor who provides a MR that solves this issue
Bounty
$5000
A bounty of $5000 for any open-source contributor who provides a MR that solves this issue
Bounty
$750
A bounty of $750 for any open-source contributor who provides a MR that solves this issue
MoSCoW
Could have
Could have feature in order to satisfy the epic/legendary.
MoSCoW
Must have
Must have feature in order to satisfy the epic/legendary.
MoSCoW
Should have
Should have feature in order to satisfy the epic/legendary.
There are questions in the ticket that can not be completed until the project owner provides clarity.
Points
1
1 man-hours worth of work for an expert with no learning curve.
Points
13
13 man-hours worth of work for an expert with no learning curve.
Points
2
2 man-hours worth of work for an expert with no learning curve.
Points
21
21 man-hours worth of work for an expert with no learning curve.
Points
3
3 man-hours worth of work for an expert with no learning curve.
Points
34
34 man-hours worth of work for an expert with no learning curve.
Points
5
5 man-hours worth of work for an expert with no learning curve.
Points
55
55 man-hours worth of work for an expert with no learning curve.
Points
8
8 man-hours worth of work for an expert with no learning curve.
Points
88
88 man-hours worth of work for an expert with no learning curve.
Priority
Backlog
This ticket has backlogged priority and is not to be worked on yet
Priority
CI Blocker
Critical priority issue that blocks CI/CD pipeline and prevents PR merges
Priority
Critical
The priority is critical
Priority
High
The priority is high
Priority
Low
The priority is low
Priority
Medium
The priority is medium
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
When an epic or legendary is in review it must be signed off by owner, tech lead, and scrum master before being marked as completed.
A ticket for learning a tool or technology that is needed to be able to do future planning and design.
State
Completed
The ticket has been fully implemented, completed, and merged with the source code. This label should only be applied once a ticket is closed.
State
Duplicate
A ticket that represents the same content as an existing ticket.
State
In Progress
A ticket that is actively being developed.
State
In Review
A ticket that has had some code completed to implement but is waiting to pass peer review and is not yet merged in.
State
Paused
This ticket's work started but wasn't finished. It's on hold (likely in a feature branch) and will be resumed later, either due to a blocker or a delay.
State
Unverified
All new tickets start in this state. A developer may set it to show the ticket is unverified. This means we haven't agreed to work on it. It will either move to a verified state or be closed as wontdo.
State
Verified
The issue has been verified by a developer as legitimate. It will be worked on and verified tickets are now considered part of the backlog.
State
Wont Do
This ticket has been decided it wont be done. This may mean the bug has been determined to not be real (cant verify) or the feature is one we have decided we dont want to adopt.
Type
Automation
Any edits or discussion about the AI automated coding system.
Type
Bug
Something that doesnt work as intended.
Type
Discussion
Anytime a ticket represents a discussion about a subject and doesnt fall into one of the other categories.
Type
Documentation
An error or improvement needed in the documentation.
Type
Epic
Any first tier epic. That is, an epic which contains only issues as children and will not have sub-epics.
Type
Feature
Some new functionality not present.
Type
Legendary
A type of Epic which will contain other Epics.
Type
Refactor
A code change that restructures existing code without changing its external behavior.
Type
Support
Someone needs help using the project.
Type
Task
A generic task that doesnt fit into the other type categories.
Type
Testing
Work exclusively focusing on fixing or expanding testing.
No Label
Type
Feature
Milestone
No items
No Milestone
Projects
Clear projects
No project
Assignees
aditya (Aditya Chhabra)
aleenaumair (Aleena Umair)
brent.edwards (Brent Edwards)
CoreRasurae (Luis Mendes)
drew (Drew Morris)
eugen.thaci (Eugen Thaci)
freemo (Jeffrey Phillips Freeman)
HAL9000 (HAL 9000)
HAL9001 (HAL9001)
hamza.khyari (Hamza Khyari)
hurui200320 (Rui Hu)
justin.morris
khird (Kyle Hird)
org.cleveragents
Clear assignees
No Assignees
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
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
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.25e6cce910to8a09b964128a09b96412toad3186a07ead3186a07etoe969851786e969851786to498f0f87ae498f0f87aeto7f0e4597177f0e459717to6d1eca444d6d1eca444dto40c102574d40c102574dtob21a41e16ab21a41e16ato9491b69f109491b69f10toea355c6433ea355c6433toab8b1451f0ab8b1451f0to7068d5d6647068d5d664to403d3e683a403d3e683ato7d218338277d21833827to0a120b2ec20a120b2ec2toe778443aade778443aadto16f8d4b94516f8d4b945to54c15c177854c15c1778tob488e10bdfb488e10bdfto2657f8c3112657f8c311to1a6648d7631a6648d763todd17cd6467dd17cd6467toe772d04193e772d04193toc9dbfa6517c9dbfa6517to2664ebfd75Review: 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.