fix(security): close async resources and leaks #435
Merged
hamza.khyari
merged 2 commits from 2026-02-26 15:19:16 +00:00
feature/m4-security-async-cleanup into master
Labels
Clear labels
auto/needs-reevaluation
controller-managed
overdue
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
Controller deferred this PR; awaiting Phase 6+ scope-evaluator or operator re-enablement.
Auto-agents controller manages this PR/issue (see tools/controller/deploy/RUNBOOK.md). Remove this label to abandon controller management.
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.
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
hamza.khyari
Notifications
Due Date
No due date set.
Blocks
#321 fix(security): close async resources and leaks
cleveragents/cleveragents-core
Reference: cleveragents/cleveragents-core#435
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/m4-security-async-cleanup"
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
Closes #321. Adds a unified async resource lifecycle and cleanup subsystem.
AsyncResourceTracker(core/async_cleanup.py) — central registry for async resources with timeout-boundedclose_all(), async context manager, and__del__finalizer that logs leaked resources by nameLangGraphBridge.cleanup_tasks_async()— awaits in-flight tasks with a deadline instead of fire-and-forget cancel; trackscancellation_reasonsStateManager.close()— properly releases checkpoint file handles and completes the RxPY BehaviorSubjectAcpEventQueue.close()— disposes all subscriptions with logged countFiles Changed
src/cleveragents/core/async_cleanup.pysrc/cleveragents/langgraph/bridge.pysrc/cleveragents/langgraph/state.pysrc/cleveragents/acp/events.pyfeatures/security_async.featurefeatures/steps/security_async_steps.pydocs/reference/async_safety.mdrobot/security_async.robotbenchmarks/security_async_cleanup_bench.pyQuality
Dependencies
Approved so that you can merge.
Code Review — PR #435: fix(security): close async resources and leaks
Reviewer: @brent.edwards | Review type: Comment-only (not blocking)
Good work on this, Hamza. The
AsyncResourceTrackerpattern is solid and the test/bench/doc coverage is well above average for a first pass. I found a few issues that should be addressed, organized by severity per the review playbook.P0 — Critical (must fix before merge)
#1 ·
src/cleveragents/core/async_cleanup.py:59–78—register()accepts resources afterclose_all()close_all()setsself._closed = Trueand clears_resources, butregister()never checks_closed. Any resource registered after shutdown is silently accepted into the (now permanently empty) tracker and will never be closed — a permanent leak.The docs (
async_safety.mdline 42) and the idempotentclose_allscenario both assume this can't happen, but nothing enforces it.P1 — High (must fix before merge)
#2 ·
async_cleanup.py:104–123—except ExceptionmissesCancelledErrorOn Python ≥ 3.9,
CancelledErrorinherits fromBaseException, notException. If a resource'sclose()is cancelled (e.g., during interpreter shutdown or outer task cancellation), theexcept Exceptionon line 119 won't catch it — the exception propagates up, skipping all remaining resources. Consider:or catching
BaseExceptionwith appropriate re-raise logic.#3 ·
langgraph/bridge.py:32,97—cancellation_reasonsdict leaks memorycancellation_reasonsusesTaskobjects as keys (strong references). Completed/cancelled tasks are never removed from this dict, so they (and their coroutine frames) are kept alive indefinitely. This is an unbounded memory leak proportional to the number of ever-cancelled tasks. Consider using aWeakKeyDictionaryor explicitly discarding entries incleanup_tasks_async()and thedone_callback.#4 ·
langgraph/state.py:109–125,151,169,182— State mutation afterclose()silently corruptsupdate_state(),reset(),load_checkpoint(), andtime_travel()all callself.state_stream.on_next()without checkingself.is_closed. Afterclose()completes theBehaviorSubjectviaon_completed(), subsequenton_next()calls are silently dropped by RxPY. This means the in-memoryself.stateis mutated but subscribers never see the update — silent data corruption.The docs say
close()"prevents further state updates" (async_safety.md:84) but the code doesn't enforce this. Add a guard:Same for
reset(),load_checkpoint(), andtime_travel().P2 — Medium (fix in follow-up PR within 3 days)
#5 ·
async_cleanup.py:145–148—__del__risksAttributeErroron partial constructionIf
__init__fails partway through,__del__will fire andself._resourcesmay not exist yet, raisingAttributeErrorduring GC. Wrap intry/except AttributeErroror usegetattr(self, '_resources', {}).#6 ·
async_cleanup.py:104–106— Sequential close is O(n × timeout)Resources are closed one-by-one. With 500 resources and a 30s timeout, worst case is 4+ hours. Consider
asyncio.gather(*[wait_for(r.close(), timeout) for r in ...])for concurrent close.#7 ·
bridge.py:62,70–77— Pending tasks orphaned after timeoutIn
cleanup_tasks_async(), tasks that land inpendingafterasyncio.wait()are logged but never re-cancelled, then_active_tasks.clear()drops all references. These orphaned tasks continue running in the background with no owner.#8 ·
bridge.py:54,62,77— Tasks added duringawait asyncio.wait()window are losttasks = list(self._active_tasks)snapshots at line 54, but new tasks can be added to_active_tasksduring theawait asyncio.wait()call. The_active_tasks.clear()on line 77 then silently drops them.#9 ·
bridge.py:35–36—__del__lacks try/except guardSame pattern as #5 — if
__init__fails partway or during interpreter shutdown,cleanup_tasks()may raise.#10 ·
acp/events.py:42—publish()afterclose()leaks eventsclose()clears_eventsand_subscriptions, but doesn't set any closed flag. Subsequentpublish()calls will re-accumulate events in_eventswith no subscribers — an unbounded memory leak. Add an_is_closedflag consistent withStateManager.#11 ·
acp/events.py:27–92— Nois_closedattributeStateManagerexposesis_closedfor callers to check, butAcpEventQueuehas no equivalent. Inconsistent API across the cleanup surface.P3 — Low (author discretion)
#12 ·
async_cleanup.py:95–100— Lock design noteThe lock correctly serializes
register()vsclose_all()— but only contingent on fixing #1. Currently a thread canregister()while another thread'sclose_all()has already set_closedand cleared the dict.#13 ·
bridge.py:31,212,214—_active_tasksis a plainset(GIL-dependent)Thread safety relies on the GIL. If this code ever runs on a free-threaded build (PEP 703), the set mutations will race. Low priority since ≥3.13 still has GIL by default.
#14 ·
bridge.py:79–103—cancel_task_with_reasondoesn't discard from_active_tasksAfter cancelling a task, it remains in
_active_tasksuntil the done callback fires. Ifcleanup_tasks_async()runs before the callback, the task appears twice. Minor, sinceasyncio.waithandles this, but worth a comment.#15 ·
state.py:190–192—close()idempotency relies on plainboolThe
if self.is_closed: returncheck is TOCTOU-racy if called from two threads simultaneously. Low priority sinceStateManageris typically single-threaded.#16 ·
acp/events.py:88–89— Non-atomic clear of two structures_subscriptions.clear()then_events.clear()— a concurrentpublish()between the two calls could see cleared subscriptions but non-cleared events. Minor since the code is single-threaded.Test Coverage Gaps
T1 (aligns with #1, P0) — No scenario for register-after-close. The Behave suite has 14 scenarios but none calls
register()afterclose_all(). This is the most critical missing test — it would have caught the P0 immediately.T2 (aligns with #4, P1) — No scenario for state mutation after close. The tests verify
is_closedis set, but never callupdate_state(),reset(), ortime_travel()afterclose()to verify the guard.T3 (aligns with #10, P2) — No scenario for publish-after-close on AcpEventQueue. Same pattern — verify behavior when the object is used after
close().T4 (aligns with #3, P1) — No scenario for cancellation_reasons cleanup. No test verifies that completed tasks are removed from the dict.
T5 —
asyncio.new_event_loop()pattern in steps is fragile. Steps at lines 103, 141, 171, 177, 253, 265 create event loops that are not always closed on failure. Consider a shared fixture orafter_scenariohook.T6 — Log handler never removed. The
_CapturingHandlerattached in the Background step (line 45) is never removed, so handlers accumulate across scenarios. Add cleanup inafter_scenario.Benchmark Issue
B1 —
TimeRegisterBatchcrashes on second ASV iteration.time_register_100()registers namesbatch-0throughbatch-99. Sincenumberis not set to1(unlikeTimeCloseAll), ASV will call this method multiple times per repeat. The second call raisesValueErroron duplicate names. Fix: addnumber = 1or reset the tracker in each call.Doc Accuracy (
async_safety.md)D1 (aligns with #4) — Line 84 claims
close()"prevents further state updates" — this is false. The code does not guardupdate_state()et al. Either fix the code (recommended) or correct the doc.D2 — Thread Safety section (lines 90–92) doesn't mention the register-after-close gap. Readers will assume
register()is safe at all times.Summary
The P0 (#1) and P1s (#2, #3, #4) should be resolved before merge. Everything else can go in a follow-up. Happy to re-review once those are addressed.
cc @hamza.khyari
d68171fd2cto376b681d70New commits pushed, approval review dismissed automatically according to repository settings
00793532aetoc406781b86