@lensmcp/memory-tracker 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +92 -0
- package/index.d.ts +7 -0
- package/index.d.ts.map +1 -0
- package/index.js +5 -0
- package/lib/context.d.ts +23 -0
- package/lib/context.d.ts.map +1 -0
- package/lib/context.js +30 -0
- package/lib/detectors.d.ts +14 -0
- package/lib/detectors.d.ts.map +1 -0
- package/lib/detectors.js +62 -0
- package/lib/emit.d.ts +31 -0
- package/lib/emit.d.ts.map +1 -0
- package/lib/emit.js +93 -0
- package/lib/owners.d.ts +47 -0
- package/lib/owners.d.ts.map +1 -0
- package/lib/owners.js +78 -0
- package/lib/track-container.d.ts +7 -0
- package/lib/track-container.d.ts.map +1 -0
- package/lib/track-container.js +155 -0
- package/lib/types.d.ts +36 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +1 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# @lensmcp/memory-tracker
|
|
2
|
+
|
|
3
|
+
Track memory growth in long-lived JavaScript containers, attribute it to the flow that caused it, and surface suspected leaks as LensMCP events.
|
|
4
|
+
|
|
5
|
+
`@lensmcp/memory-tracker` instruments the mutating methods of `Map`, `Set`, and `Array` instances in place. Every mutation updates a per-container "owner" record (item count plus a rough byte estimate) and is attributed to the active request/flow. When a flow grows a container past a threshold and the items do not shrink back, the tracker emits a `memory-retention` ("memory leak suspected") event. It also reports stale generations of disposed singletons that still retain bytes. The result is a deterministic, attributable memory signal in the LensMCP lens — instead of a flat heap graph, you see *which owner grew, by how much, and under which flow*.
|
|
6
|
+
|
|
7
|
+
It is designed to run in "light mode" inside the LensMCP node/NestJS instrumentation: zero sampling timers in the hot path, bounded per-mutation work, and a pluggable event sink so the host process forwards events to the LensMCP bus.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
yarn add @lensmcp/memory-tracker
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Most users do not install this directly. It is normally enabled through the `memory` option of `@lensmcp/nest-instrumentation` (or the node instrumentation), which calls `configureMemoryTracker` and wires the flow brackets for you. Reach for the direct API only when instrumenting a runtime that LensMCP does not auto-wire.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
Configure the tracker once at startup, track the containers you care about, then bracket each unit of work so growth can be attributed and leaks detected.
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import {
|
|
23
|
+
configureMemoryTracker,
|
|
24
|
+
trackContainer,
|
|
25
|
+
onFlowStart,
|
|
26
|
+
onFlowSettled,
|
|
27
|
+
} from '@lensmcp/memory-tracker';
|
|
28
|
+
|
|
29
|
+
// 1. Configure once. `sink` receives every memory BaseEvent; the host
|
|
30
|
+
// forwards it to the LensMCP bus. `contextGetter` lets each mutation
|
|
31
|
+
// attribute itself to the active flow (e.g. an AsyncLocalStorage store).
|
|
32
|
+
configureMemoryTracker({
|
|
33
|
+
sessionId: 'session-123',
|
|
34
|
+
sink: (event) => bus.publish(event),
|
|
35
|
+
leakItemThreshold: 50, // items of growth that flips a suspected leak (default 50)
|
|
36
|
+
staleGenerationBytesThreshold: 1024 * 1024, // bytes a disposed singleton may retain (default 1 MB)
|
|
37
|
+
settleMs: 1000, // grace period after a flow ends (default 1000)
|
|
38
|
+
contextGetter: () => currentLensmcpContext(), // optional: returns { sessionId, flowId?, requestId?, originNodeId? }
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// 2. Track a container. Patching is in-place, non-destructive, and
|
|
42
|
+
// idempotent (re-tracking the same instance is a no-op).
|
|
43
|
+
class SessionCache {
|
|
44
|
+
private readonly entries = new Map<string, Session>();
|
|
45
|
+
|
|
46
|
+
constructor(instanceId: string) {
|
|
47
|
+
trackContainer({
|
|
48
|
+
ownerInstanceId: instanceId, // identifies the owning instance
|
|
49
|
+
fieldName: 'entries', // the field being tracked
|
|
50
|
+
container: this.entries, // the Map / Set / Array to instrument
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 3. Bracket a flow. Mutations between start and settle are attributed to
|
|
56
|
+
// this flow; owners that grew past the threshold and stayed resident are
|
|
57
|
+
// flagged and emitted as `memory-retention` events.
|
|
58
|
+
onFlowStart('req-42');
|
|
59
|
+
// ... handle request: cache.entries.set(...) etc.
|
|
60
|
+
const flaggedOwnerIds = onFlowSettled('req-42'); // string[] of suspected-leak owners
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`trackContainer` only patches `Map`, `Set`, and `Array` instances — anything else is ignored. Tracked mutations are: `set` / `delete` / `clear` (Map), `add` / `delete` / `clear` (Set), and `push` / `splice` (Array).
|
|
64
|
+
|
|
65
|
+
## API
|
|
66
|
+
|
|
67
|
+
- **`configureMemoryTracker(opts)`** — Set the active session id, the event `sink`, the optional `contextGetter`, and detector thresholds (`leakItemThreshold`, `staleGenerationBytesThreshold`, `settleMs`). Returns the resolved options. Must be called before events are emitted.
|
|
68
|
+
- **`trackContainer({ ownerInstanceId, fieldName, container })`** — Instrument a `Map`/`Set`/`Array` in place so each mutation updates its owner record and emits a `memory-mutation` event. Idempotent and non-destructive.
|
|
69
|
+
- **`onFlowStart(flowId)`** — Snapshot every owner's item count at the start of a flow.
|
|
70
|
+
- **`onFlowSettled(flowId)`** — Compare each owner's attributed growth against `leakItemThreshold`; emit `memory-retention` for owners that grew and stayed resident. Returns the flagged owner ids.
|
|
71
|
+
- **`checkStaleGeneration({ logicalId, instanceId, generation, retainedBytes })`** — On singleton disposal, emit `singleton-stale-generation` when retained bytes exceed `staleGenerationBytesThreshold`. Returns whether it flagged.
|
|
72
|
+
- **`allOwners()` / `getOwner(ownerId)` / `ownerKey(ownerInstanceId, fieldName)`** — Inspect the owner registry: list owner snapshots, fetch one record, or compute an owner key (`<ownerInstanceId>::<fieldName>`).
|
|
73
|
+
- **`emitMutation` / `emitRetention` / `emitStaleGeneration`** — Low-level emit helpers that build each memory `BaseEvent` and push it to the sink (used internally; exported for advanced hosts).
|
|
74
|
+
- **`activeMemoryOptions()` / `currentMemoryContext()` / `resetMemoryTracker()`** — Read the resolved options, read the current flow context, or reset tracker state (test hook).
|
|
75
|
+
- **`markFlowStart` / `recordFlowDelta` / `flowGrowth` / `ensureOwner` / `resetOwners`** — Lower-level owner/flow primitives behind the detectors.
|
|
76
|
+
- **Types** — `MemoryEventSink`, `MemoryContext`, `ResolvedMemoryOptions`, `MemoryOwnerSnapshot`, `MemoryContainerKind`, `MemoryMutationOperation`, and the `TrackContainerArgs` input.
|
|
77
|
+
|
|
78
|
+
## How it fits
|
|
79
|
+
|
|
80
|
+
`@lensmcp/memory-tracker` is enabled by `@lensmcp/nest-instrumentation` via its `memory` option (the node instrumentation does the same). The host supplies the `sessionId`, the event `sink`, and a `contextGetter` bound to its own request context, and brackets each request with `onFlowStart` / `onFlowSettled`.
|
|
81
|
+
|
|
82
|
+
Every event is a `@lensmcp/protocol-types` `BaseEvent` with `source` and `category` of `memory`, carrying one of three payload kinds:
|
|
83
|
+
|
|
84
|
+
- `memory-mutation` — `debug` severity; per-mutation before/after counts and an estimated byte delta.
|
|
85
|
+
- `memory-retention` — `warning` severity; the "memory leak suspected" signal (owner id, flow, growth) surfaced in the lens.
|
|
86
|
+
- `singleton-stale-generation` — `warning` severity; a disposed singleton generation still retaining bytes.
|
|
87
|
+
|
|
88
|
+
These events flow through the host's sink to the LensMCP bus, where the lens renders them in the **"memory leak suspected"** channel.
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
Part of [LensMCP](https://github.com/kiwiapps-ltd/lensmcp). Apache-2.0.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { configureMemoryTracker, activeMemoryOptions, currentMemoryContext, resetMemoryTracker, } from './lib/context.js';
|
|
2
|
+
export { trackContainer, type TrackContainerArgs } from './lib/track-container.js';
|
|
3
|
+
export { ensureOwner, allOwners, getOwner, ownerKey, resetOwners, markFlowStart, recordFlowDelta, flowGrowth, } from './lib/owners.js';
|
|
4
|
+
export { emitMutation, emitRetention, emitStaleGeneration } from './lib/emit.js';
|
|
5
|
+
export { onFlowStart, onFlowSettled, checkStaleGeneration, } from './lib/detectors.js';
|
|
6
|
+
export type { MemoryEventSink, MemoryContext, ResolvedMemoryOptions, MemoryOwnerSnapshot, MemoryContainerKind, MemoryMutationOperation, } from './lib/types.js';
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
package/index.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,KAAK,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EACL,WAAW,EACX,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,WAAW,EACX,aAAa,EACb,eAAe,EACf,UAAU,GACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACjF,OAAO,EACL,WAAW,EACX,aAAa,EACb,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EACV,eAAe,EACf,aAAa,EACb,qBAAqB,EACrB,mBAAmB,EACnB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,gBAAgB,CAAC"}
|
package/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { configureMemoryTracker, activeMemoryOptions, currentMemoryContext, resetMemoryTracker, } from './lib/context.js';
|
|
2
|
+
export { trackContainer } from './lib/track-container.js';
|
|
3
|
+
export { ensureOwner, allOwners, getOwner, ownerKey, resetOwners, markFlowStart, recordFlowDelta, flowGrowth, } from './lib/owners.js';
|
|
4
|
+
export { emitMutation, emitRetention, emitStaleGeneration } from './lib/emit.js';
|
|
5
|
+
export { onFlowStart, onFlowSettled, checkStaleGeneration, } from './lib/detectors.js';
|
package/lib/context.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory tracker state. The container wrappers consult a module-level
|
|
3
|
+
* "current context" getter so each mutation can attribute itself to the
|
|
4
|
+
* active flow/request. The host wires this getter to its own
|
|
5
|
+
* AsyncLocalStorage (e.g. nest-instrumentation's
|
|
6
|
+
* `currentLensmcpContext`).
|
|
7
|
+
*/
|
|
8
|
+
import type { MemoryContext, ResolvedMemoryOptions, MemoryEventSink } from './types.js';
|
|
9
|
+
type ContextGetter = () => MemoryContext | undefined;
|
|
10
|
+
export declare function configureMemoryTracker(opts: {
|
|
11
|
+
sessionId: string;
|
|
12
|
+
sink: MemoryEventSink;
|
|
13
|
+
leakItemThreshold?: number;
|
|
14
|
+
staleGenerationBytesThreshold?: number;
|
|
15
|
+
settleMs?: number;
|
|
16
|
+
contextGetter?: ContextGetter;
|
|
17
|
+
}): ResolvedMemoryOptions;
|
|
18
|
+
export declare function activeMemoryOptions(): ResolvedMemoryOptions | undefined;
|
|
19
|
+
export declare function currentMemoryContext(): MemoryContext | undefined;
|
|
20
|
+
/** Test hook. */
|
|
21
|
+
export declare function resetMemoryTracker(): void;
|
|
22
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/lib/context.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAExF,KAAK,aAAa,GAAG,MAAM,aAAa,GAAG,SAAS,CAAC;AAWrD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,eAAe,CAAC;IACtB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,6BAA6B,CAAC,EAAE,MAAM,CAAC;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,aAAa,CAAC,EAAE,aAAa,CAAC;CAC/B,GAAG,qBAAqB,CAWxB;AAED,wBAAgB,mBAAmB,IAAI,qBAAqB,GAAG,SAAS,CAEvE;AAED,wBAAgB,oBAAoB,IAAI,aAAa,GAAG,SAAS,CAEhE;AAED,iBAAiB;AACjB,wBAAgB,kBAAkB,IAAI,IAAI,CAGzC"}
|
package/lib/context.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
let contextGetter = () => undefined;
|
|
2
|
+
let options;
|
|
3
|
+
const DEFAULTS = {
|
|
4
|
+
leakItemThreshold: 50,
|
|
5
|
+
staleGenerationBytesThreshold: 1024 * 1024,
|
|
6
|
+
settleMs: 1000,
|
|
7
|
+
};
|
|
8
|
+
export function configureMemoryTracker(opts) {
|
|
9
|
+
options = {
|
|
10
|
+
sessionId: opts.sessionId,
|
|
11
|
+
sink: opts.sink,
|
|
12
|
+
leakItemThreshold: opts.leakItemThreshold ?? DEFAULTS.leakItemThreshold,
|
|
13
|
+
staleGenerationBytesThreshold: opts.staleGenerationBytesThreshold ?? DEFAULTS.staleGenerationBytesThreshold,
|
|
14
|
+
settleMs: opts.settleMs ?? DEFAULTS.settleMs,
|
|
15
|
+
};
|
|
16
|
+
if (opts.contextGetter)
|
|
17
|
+
contextGetter = opts.contextGetter;
|
|
18
|
+
return options;
|
|
19
|
+
}
|
|
20
|
+
export function activeMemoryOptions() {
|
|
21
|
+
return options;
|
|
22
|
+
}
|
|
23
|
+
export function currentMemoryContext() {
|
|
24
|
+
return contextGetter();
|
|
25
|
+
}
|
|
26
|
+
/** Test hook. */
|
|
27
|
+
export function resetMemoryTracker() {
|
|
28
|
+
options = undefined;
|
|
29
|
+
contextGetter = () => undefined;
|
|
30
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function onFlowStart(flowId: string): void;
|
|
2
|
+
/**
|
|
3
|
+
* Compare each owner's count at flow-start vs now. Owners that grew by
|
|
4
|
+
* more than `leakItemThreshold` and didn't shrink are flagged. Returns
|
|
5
|
+
* the list of flagged owner ids (also useful for tests).
|
|
6
|
+
*/
|
|
7
|
+
export declare function onFlowSettled(flowId: string): string[];
|
|
8
|
+
export declare function checkStaleGeneration(args: {
|
|
9
|
+
logicalId: string;
|
|
10
|
+
instanceId: string;
|
|
11
|
+
generation: number;
|
|
12
|
+
retainedBytes: number;
|
|
13
|
+
}): boolean;
|
|
14
|
+
//# sourceMappingURL=detectors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"detectors.d.ts","sourceRoot":"","sources":["../../src/lib/detectors.ts"],"names":[],"mappings":"AAoBA,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAEhD;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAqBtD;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAcV"}
|
package/lib/detectors.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Suspect-leak + stale-generation detectors.
|
|
3
|
+
*
|
|
4
|
+
* `onFlowStart` / `onFlowSettled` bracket a flow: at start we snapshot
|
|
5
|
+
* every owner's count; after the flow settles we compare. If an owner
|
|
6
|
+
* grew past the threshold and didn't shrink back, we emit a
|
|
7
|
+
* `memory-retention` event.
|
|
8
|
+
*
|
|
9
|
+
* `checkStaleGeneration` is called when a singleton instance is
|
|
10
|
+
* disposed; if its sampled retained bytes exceed the threshold we emit
|
|
11
|
+
* a `singleton-stale-generation` event.
|
|
12
|
+
*/
|
|
13
|
+
import { activeMemoryOptions } from './context.js';
|
|
14
|
+
import { clearFlowStart, flowGrowth, markFlowStart, } from './owners.js';
|
|
15
|
+
import { emitRetention, emitStaleGeneration } from './emit.js';
|
|
16
|
+
export function onFlowStart(flowId) {
|
|
17
|
+
markFlowStart(flowId);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Compare each owner's count at flow-start vs now. Owners that grew by
|
|
21
|
+
* more than `leakItemThreshold` and didn't shrink are flagged. Returns
|
|
22
|
+
* the list of flagged owner ids (also useful for tests).
|
|
23
|
+
*/
|
|
24
|
+
export function onFlowSettled(flowId) {
|
|
25
|
+
const opts = activeMemoryOptions();
|
|
26
|
+
if (!opts)
|
|
27
|
+
return [];
|
|
28
|
+
const flagged = [];
|
|
29
|
+
for (const g of flowGrowth(flowId)) {
|
|
30
|
+
// Flag when THIS flow's attributed growth crosses the threshold AND
|
|
31
|
+
// the items are still resident (the container didn't shrink back).
|
|
32
|
+
if (g.growth >= opts.leakItemThreshold && g.endCount >= g.growth) {
|
|
33
|
+
emitRetention({
|
|
34
|
+
options: opts,
|
|
35
|
+
ownerId: g.owner.ownerId,
|
|
36
|
+
flowId,
|
|
37
|
+
startCount: g.startCount,
|
|
38
|
+
endCount: g.endCount,
|
|
39
|
+
growth: g.growth,
|
|
40
|
+
});
|
|
41
|
+
flagged.push(g.owner.ownerId);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
clearFlowStart(flowId);
|
|
45
|
+
return flagged;
|
|
46
|
+
}
|
|
47
|
+
export function checkStaleGeneration(args) {
|
|
48
|
+
const opts = activeMemoryOptions();
|
|
49
|
+
if (!opts)
|
|
50
|
+
return false;
|
|
51
|
+
if (args.retainedBytes > opts.staleGenerationBytesThreshold) {
|
|
52
|
+
emitStaleGeneration({
|
|
53
|
+
options: opts,
|
|
54
|
+
logicalId: args.logicalId,
|
|
55
|
+
instanceId: args.instanceId,
|
|
56
|
+
generation: args.generation,
|
|
57
|
+
retainedBytes: args.retainedBytes,
|
|
58
|
+
});
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
return false;
|
|
62
|
+
}
|
package/lib/emit.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { MemoryContext, MemoryMutationOperation, ResolvedMemoryOptions } from './types.js';
|
|
2
|
+
export declare function emitMutation(args: {
|
|
3
|
+
options: ResolvedMemoryOptions;
|
|
4
|
+
ownerId: string;
|
|
5
|
+
operation: MemoryMutationOperation;
|
|
6
|
+
beforeCount: number;
|
|
7
|
+
afterCount: number;
|
|
8
|
+
estimatedDeltaBytes: number;
|
|
9
|
+
keyPreview?: string;
|
|
10
|
+
context?: MemoryContext;
|
|
11
|
+
timestamp?: number;
|
|
12
|
+
}): void;
|
|
13
|
+
export declare function emitRetention(args: {
|
|
14
|
+
options: ResolvedMemoryOptions;
|
|
15
|
+
ownerId: string;
|
|
16
|
+
flowId: string;
|
|
17
|
+
startCount: number;
|
|
18
|
+
endCount: number;
|
|
19
|
+
growth: number;
|
|
20
|
+
context?: MemoryContext;
|
|
21
|
+
timestamp?: number;
|
|
22
|
+
}): void;
|
|
23
|
+
export declare function emitStaleGeneration(args: {
|
|
24
|
+
options: ResolvedMemoryOptions;
|
|
25
|
+
logicalId: string;
|
|
26
|
+
instanceId: string;
|
|
27
|
+
generation: number;
|
|
28
|
+
retainedBytes: number;
|
|
29
|
+
timestamp?: number;
|
|
30
|
+
}): void;
|
|
31
|
+
//# sourceMappingURL=emit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emit.d.ts","sourceRoot":"","sources":["../../src/lib/emit.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,aAAa,EACb,uBAAuB,EACvB,qBAAqB,EACtB,MAAM,YAAY,CAAC;AAiBpB,wBAAgB,YAAY,CAAC,IAAI,EAAE;IACjC,OAAO,EAAE,qBAAqB,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,uBAAuB,CAAC;IACnC,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,IAAI,CAyBP;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE;IAClC,OAAO,EAAE,qBAAqB,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,IAAI,CAwBP;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IACxC,OAAO,EAAE,qBAAqB,CAAC;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG,IAAI,CAuBP"}
|
package/lib/emit.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
let seq = 0;
|
|
2
|
+
function memId(prefix) {
|
|
3
|
+
seq = (seq + 1) % 0xffffff;
|
|
4
|
+
return `${prefix}-${seq.toString(36)}`;
|
|
5
|
+
}
|
|
6
|
+
function baseContext(options, ctx) {
|
|
7
|
+
return {
|
|
8
|
+
sessionId: ctx?.sessionId ?? options.sessionId,
|
|
9
|
+
...(ctx?.flowId ? { flowId: ctx.flowId } : {}),
|
|
10
|
+
...(ctx?.requestId ? { requestId: ctx.requestId } : {}),
|
|
11
|
+
...(ctx?.originNodeId ? { originNodeId: ctx.originNodeId } : {}),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function emitMutation(args) {
|
|
15
|
+
const { options } = args;
|
|
16
|
+
const event = {
|
|
17
|
+
id: memId('memmut'),
|
|
18
|
+
sessionId: args.context?.sessionId ?? options.sessionId,
|
|
19
|
+
timestamp: args.timestamp ?? nowMs(),
|
|
20
|
+
source: 'memory',
|
|
21
|
+
category: 'memory',
|
|
22
|
+
severity: 'debug',
|
|
23
|
+
context: baseContext(options, args.context),
|
|
24
|
+
fingerprint: `memory-mutation:${args.ownerId}:${args.operation}`,
|
|
25
|
+
title: `${args.operation} ${args.ownerId}`,
|
|
26
|
+
raw: {
|
|
27
|
+
kind: 'memory-mutation',
|
|
28
|
+
mutation: {
|
|
29
|
+
ownerNodeId: args.ownerId,
|
|
30
|
+
operation: args.operation,
|
|
31
|
+
beforeCount: args.beforeCount,
|
|
32
|
+
afterCount: args.afterCount,
|
|
33
|
+
estimatedDeltaBytes: args.estimatedDeltaBytes,
|
|
34
|
+
keyPreview: args.keyPreview,
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
options.sink(event);
|
|
39
|
+
}
|
|
40
|
+
export function emitRetention(args) {
|
|
41
|
+
const { options } = args;
|
|
42
|
+
const event = {
|
|
43
|
+
id: memId('memret'),
|
|
44
|
+
sessionId: args.context?.sessionId ?? options.sessionId,
|
|
45
|
+
timestamp: args.timestamp ?? nowMs(),
|
|
46
|
+
source: 'memory',
|
|
47
|
+
category: 'memory',
|
|
48
|
+
severity: 'warning',
|
|
49
|
+
context: { ...baseContext(options, args.context), flowId: args.flowId },
|
|
50
|
+
fingerprint: `memory-retention:${args.ownerId}`,
|
|
51
|
+
title: `Suspected leak: ${args.ownerId} grew by ${args.growth} and did not shrink`,
|
|
52
|
+
raw: {
|
|
53
|
+
kind: 'memory-retention',
|
|
54
|
+
retention: {
|
|
55
|
+
ownerId: args.ownerId,
|
|
56
|
+
flowId: args.flowId,
|
|
57
|
+
startCount: args.startCount,
|
|
58
|
+
endCount: args.endCount,
|
|
59
|
+
growth: args.growth,
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
options.sink(event);
|
|
64
|
+
}
|
|
65
|
+
export function emitStaleGeneration(args) {
|
|
66
|
+
const { options } = args;
|
|
67
|
+
const event = {
|
|
68
|
+
id: memId('memstale'),
|
|
69
|
+
sessionId: options.sessionId,
|
|
70
|
+
timestamp: args.timestamp ?? nowMs(),
|
|
71
|
+
source: 'memory',
|
|
72
|
+
category: 'memory',
|
|
73
|
+
severity: 'warning',
|
|
74
|
+
context: { sessionId: options.sessionId },
|
|
75
|
+
fingerprint: `memory-stale-generation:${args.logicalId}`,
|
|
76
|
+
title: `Stale generation retained: ${args.logicalId} gen ${args.generation} holds ${args.retainedBytes} bytes`,
|
|
77
|
+
raw: {
|
|
78
|
+
kind: 'singleton-stale-generation',
|
|
79
|
+
staleGeneration: {
|
|
80
|
+
logicalId: args.logicalId,
|
|
81
|
+
instanceId: args.instanceId,
|
|
82
|
+
generation: args.generation,
|
|
83
|
+
retainedBytes: args.retainedBytes,
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
options.sink(event);
|
|
88
|
+
}
|
|
89
|
+
function nowMs() {
|
|
90
|
+
// `Date.now` is fine in library runtime code; the workflow-script ban
|
|
91
|
+
// doesn't apply here.
|
|
92
|
+
return Date.now();
|
|
93
|
+
}
|
package/lib/owners.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owner registry. Each tracked container is an "owner" — keyed by
|
|
3
|
+
* `<ownerInstanceId>::<fieldName>`. We hold the current item count +
|
|
4
|
+
* a rough byte estimate, and the count at the start of each in-flight
|
|
5
|
+
* flow so the leak detector can compute per-flow growth.
|
|
6
|
+
*/
|
|
7
|
+
import type { MemoryContainerKind, MemoryOwnerSnapshot } from './types.js';
|
|
8
|
+
interface OwnerRecord {
|
|
9
|
+
ownerId: string;
|
|
10
|
+
ownerInstanceId: string;
|
|
11
|
+
containerKind: MemoryContainerKind;
|
|
12
|
+
fieldName: string;
|
|
13
|
+
itemCount: number;
|
|
14
|
+
estimatedBytes: number;
|
|
15
|
+
startCount: number;
|
|
16
|
+
/** itemCount captured at the start of each active flow, keyed by flowId. */
|
|
17
|
+
flowStartCounts: Map<string, number>;
|
|
18
|
+
/**
|
|
19
|
+
* Net items added by each flow's mutations, keyed by flowId. This is
|
|
20
|
+
* the *attributed* growth — only flows whose own mutations grew the
|
|
21
|
+
* container are blamed, not every flow that happened to be in flight
|
|
22
|
+
* while another flow grew it.
|
|
23
|
+
*/
|
|
24
|
+
flowDeltas: Map<string, number>;
|
|
25
|
+
}
|
|
26
|
+
export declare function ownerKey(ownerInstanceId: string, fieldName: string): string;
|
|
27
|
+
export declare function ensureOwner(args: {
|
|
28
|
+
ownerInstanceId: string;
|
|
29
|
+
fieldName: string;
|
|
30
|
+
containerKind: MemoryContainerKind;
|
|
31
|
+
}): OwnerRecord;
|
|
32
|
+
export declare function recordCount(rec: OwnerRecord, itemCount: number, estimatedBytes: number): void;
|
|
33
|
+
export declare function markFlowStart(flowId: string): void;
|
|
34
|
+
/** Attribute a net item delta to the flow whose mutation caused it. */
|
|
35
|
+
export declare function recordFlowDelta(rec: OwnerRecord, flowId: string, delta: number): void;
|
|
36
|
+
export declare function flowGrowth(flowId: string): Array<{
|
|
37
|
+
owner: OwnerRecord;
|
|
38
|
+
startCount: number;
|
|
39
|
+
endCount: number;
|
|
40
|
+
growth: number;
|
|
41
|
+
}>;
|
|
42
|
+
export declare function clearFlowStart(flowId: string): void;
|
|
43
|
+
export declare function allOwners(): MemoryOwnerSnapshot[];
|
|
44
|
+
export declare function getOwner(ownerId: string): OwnerRecord | undefined;
|
|
45
|
+
export declare function resetOwners(): void;
|
|
46
|
+
export {};
|
|
47
|
+
//# sourceMappingURL=owners.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"owners.d.ts","sourceRoot":"","sources":["../../src/lib/owners.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAE3E,UAAU,WAAW;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,mBAAmB,CAAC;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,4EAA4E;IAC5E,eAAe,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC;;;;;OAKG;IACH,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAID,wBAAgB,QAAQ,CAAC,eAAe,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAE3E;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,mBAAmB,CAAC;CACpC,GAAG,WAAW,CAkBd;AAED,wBAAgB,WAAW,CACzB,GAAG,EAAE,WAAW,EAChB,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,MAAM,GACrB,IAAI,CAGN;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAMlD;AAED,uEAAuE;AACvE,wBAAgB,eAAe,CAC7B,GAAG,EAAE,WAAW,EAChB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,IAAI,CAEN;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,KAAK,CAAC;IAChD,KAAK,EAAE,WAAW,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC,CAeD;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAKnD;AAED,wBAAgB,SAAS,IAAI,mBAAmB,EAAE,CAUjD;AAED,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAEjE;AAED,wBAAgB,WAAW,IAAI,IAAI,CAElC"}
|
package/lib/owners.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const owners = new Map();
|
|
2
|
+
export function ownerKey(ownerInstanceId, fieldName) {
|
|
3
|
+
return `${ownerInstanceId}::${fieldName}`;
|
|
4
|
+
}
|
|
5
|
+
export function ensureOwner(args) {
|
|
6
|
+
const id = ownerKey(args.ownerInstanceId, args.fieldName);
|
|
7
|
+
let rec = owners.get(id);
|
|
8
|
+
if (!rec) {
|
|
9
|
+
rec = {
|
|
10
|
+
ownerId: id,
|
|
11
|
+
ownerInstanceId: args.ownerInstanceId,
|
|
12
|
+
containerKind: args.containerKind,
|
|
13
|
+
fieldName: args.fieldName,
|
|
14
|
+
itemCount: 0,
|
|
15
|
+
estimatedBytes: 0,
|
|
16
|
+
startCount: 0,
|
|
17
|
+
flowStartCounts: new Map(),
|
|
18
|
+
flowDeltas: new Map(),
|
|
19
|
+
};
|
|
20
|
+
owners.set(id, rec);
|
|
21
|
+
}
|
|
22
|
+
return rec;
|
|
23
|
+
}
|
|
24
|
+
export function recordCount(rec, itemCount, estimatedBytes) {
|
|
25
|
+
rec.itemCount = itemCount;
|
|
26
|
+
rec.estimatedBytes = estimatedBytes;
|
|
27
|
+
}
|
|
28
|
+
export function markFlowStart(flowId) {
|
|
29
|
+
for (const rec of owners.values()) {
|
|
30
|
+
if (!rec.flowStartCounts.has(flowId)) {
|
|
31
|
+
rec.flowStartCounts.set(flowId, rec.itemCount);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Attribute a net item delta to the flow whose mutation caused it. */
|
|
36
|
+
export function recordFlowDelta(rec, flowId, delta) {
|
|
37
|
+
rec.flowDeltas.set(flowId, (rec.flowDeltas.get(flowId) ?? 0) + delta);
|
|
38
|
+
}
|
|
39
|
+
export function flowGrowth(flowId) {
|
|
40
|
+
const out = [];
|
|
41
|
+
for (const rec of owners.values()) {
|
|
42
|
+
// Only owners this flow actually mutated. `growth` is the flow's own
|
|
43
|
+
// attributed net add, not the global item-count delta.
|
|
44
|
+
const delta = rec.flowDeltas.get(flowId);
|
|
45
|
+
if (delta === undefined)
|
|
46
|
+
continue;
|
|
47
|
+
out.push({
|
|
48
|
+
owner: rec,
|
|
49
|
+
startCount: rec.flowStartCounts.get(flowId) ?? 0,
|
|
50
|
+
endCount: rec.itemCount,
|
|
51
|
+
growth: delta,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
export function clearFlowStart(flowId) {
|
|
57
|
+
for (const rec of owners.values()) {
|
|
58
|
+
rec.flowStartCounts.delete(flowId);
|
|
59
|
+
rec.flowDeltas.delete(flowId);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export function allOwners() {
|
|
63
|
+
return [...owners.values()].map((rec) => ({
|
|
64
|
+
ownerId: rec.ownerId,
|
|
65
|
+
ownerInstanceId: rec.ownerInstanceId,
|
|
66
|
+
containerKind: rec.containerKind,
|
|
67
|
+
fieldName: rec.fieldName,
|
|
68
|
+
itemCount: rec.itemCount,
|
|
69
|
+
estimatedBytes: rec.estimatedBytes,
|
|
70
|
+
growthSinceStart: rec.itemCount - rec.startCount,
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
export function getOwner(ownerId) {
|
|
74
|
+
return owners.get(ownerId);
|
|
75
|
+
}
|
|
76
|
+
export function resetOwners() {
|
|
77
|
+
owners.clear();
|
|
78
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"track-container.d.ts","sourceRoot":"","sources":["../../src/lib/track-container.ts"],"names":[],"mappings":"AAiBA,MAAM,WAAW,kBAAkB;IACjC,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;CACpB;AAKD,wBAAgB,cAAc,CAAC,IAAI,EAAE,kBAAkB,GAAG,IAAI,CA6B7D"}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Container tracking. Wraps the mutating methods of a Map / Set / Array
|
|
3
|
+
* so each mutation:
|
|
4
|
+
* 1. updates the owner's item count + byte estimate,
|
|
5
|
+
* 2. emits a `memory-mutation` event attributed to the active flow.
|
|
6
|
+
*
|
|
7
|
+
* The wrapping is in-place (we patch the instance's own methods) and
|
|
8
|
+
* non-destructive: original behaviour always runs, return values pass
|
|
9
|
+
* through, and patching is idempotent (guarded by a Symbol flag).
|
|
10
|
+
*/
|
|
11
|
+
import { activeMemoryOptions, currentMemoryContext } from './context.js';
|
|
12
|
+
import { ensureOwner, recordCount, recordFlowDelta } from './owners.js';
|
|
13
|
+
import { emitMutation } from './emit.js';
|
|
14
|
+
const PATCHED = Symbol.for('@lensmcp/memory-tracker/patched');
|
|
15
|
+
/** Rough per-item byte estimate; good enough for growth-trend detection. */
|
|
16
|
+
const BYTES_PER_ITEM = 64;
|
|
17
|
+
export function trackContainer(args) {
|
|
18
|
+
const { container } = args;
|
|
19
|
+
if (!container || typeof container !== 'object')
|
|
20
|
+
return;
|
|
21
|
+
if (container[PATCHED])
|
|
22
|
+
return;
|
|
23
|
+
let kind;
|
|
24
|
+
if (container instanceof Map) {
|
|
25
|
+
kind = 'Map';
|
|
26
|
+
patchMap(args, container);
|
|
27
|
+
}
|
|
28
|
+
else if (container instanceof Set) {
|
|
29
|
+
kind = 'Set';
|
|
30
|
+
patchSet(args, container);
|
|
31
|
+
}
|
|
32
|
+
else if (Array.isArray(container)) {
|
|
33
|
+
kind = 'Array';
|
|
34
|
+
patchArray(args, container);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
container[PATCHED] = true;
|
|
40
|
+
// Register the owner eagerly (at its current size) so a subsequent
|
|
41
|
+
// `markFlowStart` snapshots a baseline even before the first mutation.
|
|
42
|
+
const initial = sizeOf(container);
|
|
43
|
+
const owner = ensureOwner({
|
|
44
|
+
ownerInstanceId: args.ownerInstanceId,
|
|
45
|
+
fieldName: args.fieldName,
|
|
46
|
+
containerKind: kind,
|
|
47
|
+
});
|
|
48
|
+
recordCount(owner, initial, initial * BYTES_PER_ITEM);
|
|
49
|
+
}
|
|
50
|
+
function sizeOf(container) {
|
|
51
|
+
if (container instanceof Map || container instanceof Set)
|
|
52
|
+
return container.size;
|
|
53
|
+
if (Array.isArray(container))
|
|
54
|
+
return container.length;
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
function afterMutation(args, kind, operation, before, keyPreview) {
|
|
58
|
+
const opts = activeMemoryOptions();
|
|
59
|
+
if (!opts)
|
|
60
|
+
return;
|
|
61
|
+
const after = sizeOf(args.container);
|
|
62
|
+
const owner = ensureOwner({
|
|
63
|
+
ownerInstanceId: args.ownerInstanceId,
|
|
64
|
+
fieldName: args.fieldName,
|
|
65
|
+
containerKind: kind,
|
|
66
|
+
});
|
|
67
|
+
recordCount(owner, after, after * BYTES_PER_ITEM);
|
|
68
|
+
const ctx = currentMemoryContext();
|
|
69
|
+
// Attribute this mutation's net delta to the active flow so the leak
|
|
70
|
+
// detector blames the flow that actually grew the container. Keyed by
|
|
71
|
+
// requestId (preferred — the interceptor brackets onFlowStart/Settled
|
|
72
|
+
// by requestId) with flowId as the fallback for non-request flows.
|
|
73
|
+
const flowKey = ctx?.requestId ?? ctx?.flowId;
|
|
74
|
+
if (flowKey)
|
|
75
|
+
recordFlowDelta(owner, flowKey, after - before);
|
|
76
|
+
emitMutation({
|
|
77
|
+
options: opts,
|
|
78
|
+
ownerId: owner.ownerId,
|
|
79
|
+
operation,
|
|
80
|
+
beforeCount: before,
|
|
81
|
+
afterCount: after,
|
|
82
|
+
estimatedDeltaBytes: (after - before) * BYTES_PER_ITEM,
|
|
83
|
+
keyPreview,
|
|
84
|
+
context: ctx,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
function patchMap(args, map) {
|
|
88
|
+
const origSet = map.set.bind(map);
|
|
89
|
+
const origDelete = map.delete.bind(map);
|
|
90
|
+
const origClear = map.clear.bind(map);
|
|
91
|
+
map.set = (k, v) => {
|
|
92
|
+
const before = map.size;
|
|
93
|
+
const r = origSet(k, v);
|
|
94
|
+
afterMutation(args, 'Map', 'set', before, previewKey(k));
|
|
95
|
+
return r;
|
|
96
|
+
};
|
|
97
|
+
map.delete = (k) => {
|
|
98
|
+
const before = map.size;
|
|
99
|
+
const r = origDelete(k);
|
|
100
|
+
afterMutation(args, 'Map', 'delete', before, previewKey(k));
|
|
101
|
+
return r;
|
|
102
|
+
};
|
|
103
|
+
map.clear = () => {
|
|
104
|
+
const before = map.size;
|
|
105
|
+
origClear();
|
|
106
|
+
afterMutation(args, 'Map', 'clear', before);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
function patchSet(args, set) {
|
|
110
|
+
const origAdd = set.add.bind(set);
|
|
111
|
+
const origDelete = set.delete.bind(set);
|
|
112
|
+
const origClear = set.clear.bind(set);
|
|
113
|
+
set.add = (v) => {
|
|
114
|
+
const before = set.size;
|
|
115
|
+
const r = origAdd(v);
|
|
116
|
+
afterMutation(args, 'Set', 'add', before, previewKey(v));
|
|
117
|
+
return r;
|
|
118
|
+
};
|
|
119
|
+
set.delete = (v) => {
|
|
120
|
+
const before = set.size;
|
|
121
|
+
const r = origDelete(v);
|
|
122
|
+
afterMutation(args, 'Set', 'delete', before, previewKey(v));
|
|
123
|
+
return r;
|
|
124
|
+
};
|
|
125
|
+
set.clear = () => {
|
|
126
|
+
const before = set.size;
|
|
127
|
+
origClear();
|
|
128
|
+
afterMutation(args, 'Set', 'clear', before);
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function patchArray(args, arr) {
|
|
132
|
+
const origPush = arr.push.bind(arr);
|
|
133
|
+
const origSplice = arr.splice.bind(arr);
|
|
134
|
+
arr.push = (...items) => {
|
|
135
|
+
const before = arr.length;
|
|
136
|
+
const r = origPush(...items);
|
|
137
|
+
afterMutation(args, 'Array', 'push', before);
|
|
138
|
+
return r;
|
|
139
|
+
};
|
|
140
|
+
arr.splice = ((start, deleteCount, ...items) => {
|
|
141
|
+
const before = arr.length;
|
|
142
|
+
const r = deleteCount === undefined
|
|
143
|
+
? origSplice(start)
|
|
144
|
+
: origSplice(start, deleteCount, ...items);
|
|
145
|
+
afterMutation(args, 'Array', items.length > 0 ? 'push' : 'delete', before);
|
|
146
|
+
return r;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function previewKey(k) {
|
|
150
|
+
if (typeof k === 'string')
|
|
151
|
+
return k.slice(0, 40);
|
|
152
|
+
if (typeof k === 'number' || typeof k === 'boolean')
|
|
153
|
+
return String(k);
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
package/lib/types.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public types for `@lensmcp/memory-tracker`. The tracker emits
|
|
3
|
+
* `BaseEvent`s through a pluggable sink (same shape as
|
|
4
|
+
* `@lensmcp/nest-instrumentation`'s EventSink) so the host process can
|
|
5
|
+
* forward them to the LensMCP bus.
|
|
6
|
+
*/
|
|
7
|
+
import type { BaseEvent, MemoryContainerKind, MemoryMutationOperation } from '@lensmcp/protocol-types';
|
|
8
|
+
export type { MemoryContainerKind, MemoryMutationOperation };
|
|
9
|
+
export type MemoryEventSink = (event: BaseEvent) => void;
|
|
10
|
+
export interface MemoryContext {
|
|
11
|
+
sessionId: string;
|
|
12
|
+
flowId?: string;
|
|
13
|
+
requestId?: string;
|
|
14
|
+
originNodeId?: string;
|
|
15
|
+
}
|
|
16
|
+
/** Resolved options after defaults are applied. */
|
|
17
|
+
export interface ResolvedMemoryOptions {
|
|
18
|
+
sessionId: string;
|
|
19
|
+
sink: MemoryEventSink;
|
|
20
|
+
/** Owner growth (in items) within a flow that flips a suspected leak. Default 50. */
|
|
21
|
+
leakItemThreshold: number;
|
|
22
|
+
/** Bytes retained by a disposed singleton that flags stale-generation. Default 1MB. */
|
|
23
|
+
staleGenerationBytesThreshold: number;
|
|
24
|
+
/** ms to wait after flow end before checking owner shrinkage. Default 1000. */
|
|
25
|
+
settleMs: number;
|
|
26
|
+
}
|
|
27
|
+
export interface MemoryOwnerSnapshot {
|
|
28
|
+
ownerId: string;
|
|
29
|
+
ownerInstanceId: string;
|
|
30
|
+
containerKind: MemoryContainerKind;
|
|
31
|
+
fieldName: string;
|
|
32
|
+
itemCount: number;
|
|
33
|
+
estimatedBytes: number;
|
|
34
|
+
growthSinceStart: number;
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAEvG,YAAY,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,CAAC;AAE7D,MAAM,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;AAEzD,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,mDAAmD;AACnD,MAAM,WAAW,qBAAqB;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,eAAe,CAAC;IACtB,qFAAqF;IACrF,iBAAiB,EAAE,MAAM,CAAC;IAC1B,uFAAuF;IACvF,6BAA6B,EAAE,MAAM,CAAC;IACtC,+EAA+E;IAC/E,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,mBAAmB,CAAC;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,MAAM,CAAC;CAC1B"}
|
package/lib/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lensmcp/memory-tracker",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./index.js",
|
|
6
|
+
"module": "./index.js",
|
|
7
|
+
"types": "./index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
"./package.json": "./package.json",
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./index.d.ts",
|
|
12
|
+
"import": "./index.js",
|
|
13
|
+
"default": "./index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@lensmcp/protocol-types": "1.0.0",
|
|
18
|
+
"tslib": "^2.3.0"
|
|
19
|
+
},
|
|
20
|
+
"license": "Apache-2.0",
|
|
21
|
+
"homepage": "https://github.com/kiwiapps-ltd/lensmcp#readme",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/kiwiapps-ltd/lensmcp/issues"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"description": "LensMCP container/memory mutation tracking (Map/Set/Array instrumentation).",
|
|
32
|
+
"keywords": [
|
|
33
|
+
"lensmcp",
|
|
34
|
+
"mcp",
|
|
35
|
+
"observability",
|
|
36
|
+
"ai-agents",
|
|
37
|
+
"claude",
|
|
38
|
+
"memory",
|
|
39
|
+
"leak-detection"
|
|
40
|
+
],
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "git+https://github.com/kiwiapps-ltd/lensmcp.git",
|
|
44
|
+
"directory": "libs/memory-tracker"
|
|
45
|
+
}
|
|
46
|
+
}
|