Cancelled stream retains callbacks
Detect: Heap snapshots show completed requests reachable through listeners.
Recover: Unregister handlers in a guaranteed cleanup path.
Bound retained state and resource lifetimes so long-running agents remain stable as conversations, tools, and tenants accumulate.
Memory leak mitigation addresses resources that remain reachable or allocated after their useful lifetime. Agent runtimes are especially exposed because conversation histories, tool transcripts, callback closures, streaming buffers, and background tasks can survive many turns. GPU memory adds a separate distinction between live tensors, cached allocator blocks, and key-value cache retained for active sequences.
A rising resident-set size is a symptom rather than proof of a leak. Capacity growth, allocator fragmentation, unbounded caches, native-library allocations, and true lost ownership require different remedies. The architectural goal is explicit ownership, bounded cardinality, and observable release at session, request, and worker boundaries.
A prototype should run repeated conversations in one process and measure whether retained objects return toward a stable baseline.
Production introduces session expiration, bounded caches, stream cancellation, task ownership, and memory-aware admission limits.
Enterprise operation adds long-duration soak tests, per-tenant quotas, heap sampling, and controlled worker recycling as a containment mechanism while root causes are repaired.
Keeps durable history outside the worker and loads only the required turn window.
Closes clients, cancels child tasks, and releases buffers when a request ends.
Enforces byte and entry limits with eviction and expiry rather than unlimited memoization.
Separates heap objects, native allocation, process residency, and accelerator allocation.
Limits concurrent contexts using measured memory cost, not request count alone.
flowchart LR
H["Durable session history"] --> W["Bounded turn window"]
W --> S["Request resource scope"]
S --> B["Tool buffers and child tasks"]
B --> C["Completion or cancellation"]
C --> X["Close handles and release references"]
P["Heap and GPU telemetry"] --> Q["Drain oversized worker"]Attach every tool stream, task, and temporary artifact to an explicit request or session scope.
Retrieve current context while keeping full history in durable external storage.
Record memory before and after representative turns and correlate with session and token counts.
Cancel unfinished tasks, release stream readers, and remove callbacks when the caller disconnects or the task ends.
Remove idle sessions and cache entries under byte budgets and tenant limits.
Drain and replace a worker exceeding its memory envelope while retaining diagnostic evidence.
Logistics · Illustrative enterprise scenario, not a reported customer outcome.
Dispatchers keep long conversations open while checking routes, driver status, and delivery exceptions.
Workers retain every tool response and disconnected stream listener, so memory grows across shift changes.
Support ongoing conversations while bounding each worker footprint and preserving cancellation behavior.
The service stores full transcripts in a database, loads a compact working window, and scopes tracking streams to active requests.
If a native map library continues growing outside the managed heap, the worker drains while profiles identify the native allocation path.
Measure memory per active session, retained bytes after cancellation, and out-of-memory termination rate; worker restarts are containment rather than evidence of a repaired leak.
| Decision | Benefit | Cost |
|---|---|---|
| External session history | Bounds local working memory. | Adds read latency and serialization overhead. |
| Aggressive cache eviction | Reduces retention and tenant interference. | May increase model or data-fetch work. |
| Worker recycling | Limits the duration of an unresolved leak. | Interrupts warm caches and can conceal the underlying defect. |
Detect: Heap snapshots show completed requests reachable through listeners.
Recover: Unregister handlers in a guaranteed cleanup path.
Detect: Cache occupancy and active-token counts rise before allocation errors.
Recover: Reduce admission and safely cancel or defer excess sequences.
Measure native and accelerator allocations alongside application objects.
Apply byte budgets because transcript and embedding sizes vary.
Use ownership and expiry policies that preserve active requests.