@lensmcp/core 1.25.44 → 1.25.46
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/lib/answer-budget.d.ts +42 -17
- package/lib/answer-budget.js +2 -2
- package/lib/flow-shape.d.ts +6 -6
- package/lib/patterns.d.ts +11 -1
- package/lib/patterns.js +1 -1
- package/lib/performance-window.d.ts +11 -5
- package/lib/performance-window.js +1 -1
- package/package.json +2 -2
package/lib/answer-budget.d.ts
CHANGED
|
@@ -11,8 +11,17 @@ export declare const DEFAULT_ANSWER_BUDGET_BYTES: number;
|
|
|
11
11
|
export declare const ANSWER_BUDGET_ENV = "LENSMCP_ANSWER_BUDGET_BYTES";
|
|
12
12
|
/** A budget below this cannot hold the note that says an answer was cut, so it is raised to it. */
|
|
13
13
|
export declare const MIN_ANSWER_BUDGET_BYTES: number;
|
|
14
|
-
/** The key a cut document carries its
|
|
14
|
+
/** The key a cut document carries its {@link AnswerCut} under. */
|
|
15
15
|
export declare const ANSWER_CUT_KEY = "cutToFit";
|
|
16
|
+
/**
|
|
17
|
+
* Longest a cut's `note` may be, in UTF-8 bytes. The note used to be a paragraph of about 700 characters that listed
|
|
18
|
+
* every cut list, repeated the tool's hint and ended by telling the agent to start the lens with the budget off. One
|
|
19
|
+
* Codex lead read it 45 times in a run, and the last sentence pushed agents toward larger answers
|
|
20
|
+
* (issues/closed/foodguard-155). Now the details are fields of the cut, and the note is one short sentence that says
|
|
21
|
+
* how to read them. How to turn the budget off is for the person: it is in the docs and on the dashboard, never in an
|
|
22
|
+
* answer to an agent.
|
|
23
|
+
*/
|
|
24
|
+
export declare const MAX_CUT_NOTE_BYTES = 120;
|
|
16
25
|
/** Longest string left whole in an item of a list that is over its budget — a message and about fifteen stack frames. */
|
|
17
26
|
export declare const FITTED_STRING_CHARS = 1500;
|
|
18
27
|
/** A string at least this long is stated once per list; a repeat becomes a reference to the first. */
|
|
@@ -83,29 +92,45 @@ export interface ListFit<T> {
|
|
|
83
92
|
export declare function fitList<T>(items: readonly T[], budgetBytes: number, opts?: ListFitOptions): ListFit<T>;
|
|
84
93
|
/** Split a budget between several claims: a small one is granted whole, and the large ones share what is left evenly. */
|
|
85
94
|
export declare function shareBudget(sizes: readonly number[], budgetBytes: number): number[];
|
|
86
|
-
/**
|
|
95
|
+
/** One list that lost items: how many it holds, how many are shown, and which. */
|
|
96
|
+
export interface ListCut {
|
|
97
|
+
list: string;
|
|
98
|
+
total: number;
|
|
99
|
+
returned: number;
|
|
100
|
+
kept: 'newest' | 'first' | 'last';
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* What a cut answer says about itself, under {@link ANSWER_CUT_KEY}. The details are fields an agent reads, and a
|
|
104
|
+
* field is left out when it has nothing to say, so the whole object is a few hundred bytes. It used to carry a
|
|
105
|
+
* paragraph-long note and every count, zeros included (issues/closed/foodguard-155).
|
|
106
|
+
*/
|
|
87
107
|
export interface AnswerCut {
|
|
88
|
-
/** The budget it was fitted to. */
|
|
89
|
-
|
|
90
|
-
/** What the whole answer weighs. */
|
|
91
|
-
|
|
92
|
-
/** Each list that lost items
|
|
93
|
-
lists
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
shortenedStrings: number;
|
|
100
|
-
repeatedStrings: number;
|
|
101
|
-
/** Cutting lists was not enough: large values elsewhere in the document were shrunk too. */
|
|
108
|
+
/** The budget it was fitted to, in UTF-8 bytes. */
|
|
109
|
+
budget: number;
|
|
110
|
+
/** What the whole answer weighs, in UTF-8 bytes (`null` on the wire for one that cannot be measured). */
|
|
111
|
+
original: number;
|
|
112
|
+
/** Each list that lost items. Absent when no list did. */
|
|
113
|
+
lists?: ListCut[];
|
|
114
|
+
/** How many long texts were cut to their head (`…[lensmcp truncated: N more chars]`). */
|
|
115
|
+
shortened?: number;
|
|
116
|
+
/** How many texts repeated between items are stated once and referenced (`…[lensmcp: same text as …]`). */
|
|
117
|
+
repeated?: number;
|
|
118
|
+
/** Cutting lists was not enough: large values elsewhere in the document were shrunk too (`__lensmcpTruncation`). */
|
|
102
119
|
clamped?: true;
|
|
103
120
|
/** The values it holds that were sent whole, whatever the budget ({@link AnswerFitOptions.whole}). */
|
|
104
121
|
whole?: string[];
|
|
122
|
+
/** Where the rest can be read, when the caller knows ({@link AnswerFitOptions.more}). */
|
|
123
|
+
more?: string;
|
|
124
|
+
/** One sentence on how to read the fields above, at most {@link MAX_CUT_NOTE_BYTES}. */
|
|
105
125
|
note: string;
|
|
106
126
|
}
|
|
127
|
+
/** The note for a cut: how to read its fields. It never names a way to turn the budget off (issues/closed/foodguard-155). */
|
|
128
|
+
export declare function cutNote(cut: Pick<AnswerCut, 'lists' | 'more'>): string;
|
|
107
129
|
export interface AnswerFitOptions {
|
|
108
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* Where the rest can be read, such as the tool that pages this list. It goes in the cut's `more` field: keep it to a
|
|
132
|
+
* line, because every cut answer of that tool carries it.
|
|
133
|
+
*/
|
|
109
134
|
more?: string;
|
|
110
135
|
/** Per top-level list: the end that holds its newest items, for a ring whose items carry no time. */
|
|
111
136
|
newest?: Readonly<Record<string, ListEnd>>;
|
package/lib/answer-budget.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`,
|
|
1
|
+
"use strict";var L=Object.defineProperty;var m=(e,n)=>L(e,"name",{value:n,configurable:!0});var Y=Object.defineProperty,f=m((e,n)=>Y(e,"name",{value:n,configurable:!0}),"h");import{boundedClone as z}from"@lensmcp/protocol-types";export const DEFAULT_ANSWER_BUDGET_BYTES=24*1024,ANSWER_BUDGET_ENV="LENSMCP_ANSWER_BUDGET_BYTES",MIN_ANSWER_BUDGET_BYTES=2*1024,ANSWER_CUT_KEY="cutToFit",MAX_CUT_NOTE_BYTES=120,FITTED_STRING_CHARS=1500,REPEATED_STRING_MIN_CHARS=200;const C=600,V=32,H=new Set(["timestamp","startedAt","startTime","at","emittedAt","lastSeenAt","endedAt","endTime","t","ts","time"]),K=f(e=>typeof e=="number"&&e>=1e11&&e<=1e14,"isEpochMs"),J=.95;export function answerBudgetBytes(e=process.env){const n=e[ANSWER_BUDGET_ENV];if(n===void 0||n.trim()==="")return DEFAULT_ANSWER_BUDGET_BYTES;const r=Number(n);return!Number.isFinite(r)||r<0?DEFAULT_ANSWER_BUDGET_BYTES:r===0?Number.POSITIVE_INFINITY:Math.max(MIN_ANSWER_BUDGET_BYTES,Math.floor(r))}m(answerBudgetBytes,"answerBudgetBytes"),f(answerBudgetBytes,"answerBudgetBytes");export function utf8Bytes(e){let n=0;for(let r=0;r<e.length;r++){const o=e.charCodeAt(r);o<128?n+=1:o<2048?n+=2:o>=55296&&o<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(n+=4,r+=1):n+=3}return n}m(utf8Bytes,"utf8Bytes"),f(utf8Bytes,"utf8Bytes");export function jsonBytes(e){let n;try{n=JSON.stringify(e)}catch{return Number.POSITIVE_INFINITY}return n===void 0?0:utf8Bytes(n)}m(jsonBytes,"jsonBytes"),f(jsonBytes,"jsonBytes");const R=f(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isRecord");function O(e){if(!R(e))return!1;const n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}m(O,"C"),f(O,"isPlain");export function newestEndOf(e){const n=e[0];if(e.length<2||!R(n))return;let r;for(const o of Object.keys(n)){if(typeof n[o]!="number"||!(H.has(o)||K(n[o])))continue;let s=0,i=0,u=!0,a=n[o];for(let y=1;y<e.length;y++){const x=e[y],d=R(x)?x[o]:void 0;if(typeof d!="number"){u=!1;break}d>a?s+=1:d<a&&(i+=1),a=d}const h=s+i;if(!u||h===0)continue;const l=Math.max(s,i)/h;l>=J&&(!r||l>r.agreement)&&(r={end:s>=i?"end":"start",agreement:l})}return r?.end}m(newestEndOf,"newestEndOf"),f(newestEndOf,"newestEndOf");export function newestFirst(e){return newestEndOf(e)==="end"?[...e].reverse():e.slice()}m(newestFirst,"newestFirst"),f(newestFirst,"newestFirst");export function shortenText(e,n){if(e.length<=n)return e;let r=Math.max(0,n);const o=e.lastIndexOf(`
|
|
2
|
+
`,r);return o>=r/2&&(r=o),r>0&&(e.charCodeAt(r-1)&64512)===55296&&(r-=1),`${e.slice(0,r)}\u2026[lensmcp truncated: ${e.length-r} more chars]`}m(shortenText,"shortenText"),f(shortenText,"shortenText");export function fitList(e,n,r={}){const o=e.length,s=e.reduce((c,w)=>c+jsonBytes(w)+1,2);if(s<=n)return{items:e.slice(),total:o,returned:o,kept:"all",shortenedStrings:0,repeatedStrings:0,bytes:s};const i=r.newest??newestEndOf(e),u=i??r.keep??"start",a=r.name??"items",h=r.maxStringChars??FITTED_STRING_CHARS,l=u==="start"?e:[...e].reverse(),y=String(Math.max(0,o-1)).length,x=new Map,d=[],b=[];let E=2,_=0,$=0;for(let c=0;c<l.length;c++){const w=new Map,T=[];let M=0;const A=f((t,p,g,G,W)=>{if(typeof t=="string"){if(t.length>=REPEATED_STRING_MIN_CHARS){const S=x.get(t)??w.get(t);if(S)return T.push({holder:G,key:W,owner:S.owner,path:S.path}),`\u2026[lensmcp: same text as ${a}[${"9".repeat(y)}]${S.path}]`;w.set(t,{owner:c,path:p})}return t.length>h?(M+=1,shortenText(t,h)):t}if(g>=V)return t;if(Array.isArray(t)){const S=[];return t.forEach((I,D)=>S.push(A(I,`${p}[${D}]`,g+1,S,D))),S}if(O(t)){const S={};for(const I of Object.keys(t))S[I]=A(t[I],`${p}.${I}`,g+1,S,I);return S}return t},"slim"),B=[];let N=A(l[c],"",0,B,0),v=jsonBytes(N)+1;if(b.length===0&&E+v>n)N=F(l[c],Math.max(0,n-E-1)),v=jsonBytes(N)+1,T.length=0,w.clear(),M=1;else if(E+v>n)break;b.push(N),E+=v,_+=M,$+=T.length;for(const[t,p]of w)x.set(t,p);for(const t of T)d.push(t.holder===B?{...t,holder:b,key:b.length-1}:t)}const k=b.length,j=f(c=>u==="start"?c:k-1-c,"indexOf");if(u==="end"){for(const c of d)c.holder===b&&(c.key=j(c.key));b.reverse()}for(const c of d)c.holder[c.key]=`\u2026[lensmcp: same text as ${a}[${j(c.owner)}]${c.path}]`;return{items:b,total:o,returned:k,kept:k===o?"all":i?"newest":u==="start"?"first":"last",shortenedStrings:_,repeatedStrings:$,bytes:jsonBytes(b)}}m(fitList,"fitList"),f(fitList,"fitList");function F(e,n){let r=Math.max(256,n),o=e;for(let s=0;s<6;s++){if(o=z(e,{rawByteLimit:r,maxStringBytes:Math.min(2e3,Math.max(128,Math.floor(r/4))),maxArrayItems:64}).value,jsonBytes(o)<=n)return o;r=Math.floor(r*.6)}return o}m(F,"D"),f(F,"clampTo");export function shareBudget(e,n){const r=e.map((i,u)=>({size:i,index:u})).sort((i,u)=>i.size-u.size),o=new Array(e.length).fill(0);let s=Math.max(0,n);return r.forEach(({size:i,index:u},a)=>{const h=Math.floor(s/(r.length-a));o[u]=Math.min(i,h),s-=o[u]}),o}m(shareBudget,"shareBudget"),f(shareBudget,"shareBudget");export function cutNote(e){return(e.lists?.length?"Cut to fit: each list in `lists` shows `returned` of `total`; every other count is of the whole.":"Cut to fit: large values were shortened; every count is of the whole.")+(e.more?" Rest: see `more`.":"")}m(cutNote,"cutNote"),f(cutNote,"cutNote");function P(e,n){const r={...e},o=new WeakSet([r]),s=[];let i=0;for(const u of n){const a=u.split("."),h=a[a.length-1];let l=r;for(const y of a.slice(0,-1)){const x=l[y];if(!O(x)){l=void 0;break}const d=o.has(x)?x:{...x};o.add(d),l[y]=d,l=d}!l||l[h]===void 0||l[h]===null||(s.push({keys:a,value:l[h]}),i+=jsonBytes(l[h]),l[h]=null)}return s.length?{body:r,parts:s,bytes:i}:void 0}m(P,"K"),f(P,"holdWhole");function U(e,n){for(const{keys:r,value:o}of n){let s=e;for(const i of r.slice(0,-1)){const u=s[i],a=O(u)?u:{};s[i]=a,s=a}s[r[r.length-1]]=o}return e}m(U,"z"),f(U,"putBack");export function fitAnswer(e,n,r={}){if(!Number.isFinite(n)||e===null||typeof e!="object")return{value:e};const o=jsonBytes(e);if(o<=n)return{value:e};const s=r.whole?.length&&O(e)?P(e,r.whole):void 0,i=s?s.body:e,u=s?jsonBytes(i):o,a=s?Math.max(MIN_ANSWER_BUDGET_BYTES,n-s.bytes):n;if(u<=a)return{value:e};const h=[];let l=0,y=0,x=!1,d;const b=f(()=>(d={budget:n,original:o,...h.length?{lists:h}:{},...l?{shortened:l}:{},...y?{repeated:y}:{},...x?{clamped:!0}:{},...s?{whole:s.parts.map(t=>t.keys.join("."))}:{},...r.more?{more:r.more}:{},note:cutNote({lists:h,more:r.more})},d),"describe"),E=f(t=>({value:s?U(t,s.parts):t,cut:d}),"done");if(Array.isArray(i)){const t=fitList(i,a);return t.kept!=="all"&&h.push({list:"items",total:t.total,returned:t.returned,kept:t.kept}),l=t.shortenedStrings,y=t.repeatedStrings,b(),E(t.items)}if(!O(i))return{value:e};const _=Object.keys(i),$=_.filter(t=>Array.isArray(i[t])&&i[t].length>0),k=$.map(t=>jsonBytes(i[t])),j=u-k.reduce((t,p)=>t+p,0),c=shareBudget(k,a-j-C),w={};$.forEach((t,p)=>{if(k[p]<=c[p])return;const g=fitList(i[t],c[p],{name:t,...r.newest?.[t]?{newest:r.newest[t]}:{}});w[t]=g.items,g.kept!=="all"&&h.push({list:t,total:g.total,returned:g.returned,kept:g.kept}),l+=g.shortenedStrings,y+=g.repeatedStrings});const T=f(t=>({[ANSWER_CUT_KEY]:b(),...t}),"assemble"),M={};for(const t of _)M[t]=t in w?w[t]:i[t];let A=T(M);if(jsonBytes(A)<=a)return E(A);x=!0;let B=Math.max(512,a-C);for(let t=0;t<6;t++){if(A=T(F(M,B)),jsonBytes(A)<=a)return E(A);B=Math.floor(B*.6)}const N={};let v=C;for(const t of _){const p=i[t];if(p!==null&&typeof p=="object")continue;const g=jsonBytes(p)+utf8Bytes(t)+4;if(v+g>a)break;N[t]=p,v+=g}return E(T(N))}m(fitAnswer,"fitAnswer"),f(fitAnswer,"fitAnswer");
|
package/lib/flow-shape.d.ts
CHANGED
|
@@ -74,9 +74,9 @@ export declare function trimFlowEvent(event: BaseEvent, opts?: FlowShapeOptions)
|
|
|
74
74
|
outcome?: "returned" | "threw" | undefined;
|
|
75
75
|
calleeRequestId?: string | undefined;
|
|
76
76
|
hop?: true | undefined;
|
|
77
|
-
source: "
|
|
78
|
-
category: "
|
|
79
|
-
severity: "error" | "
|
|
77
|
+
source: "gateway" | "ai" | "db" | "redis" | "queue" | "external" | "visual" | "react" | "memory" | "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "valtio" | "nestjs" | "nextjs" | "perf" | "security" | "lens" | "custom";
|
|
78
|
+
category: "ai" | "db" | "visual" | "memory" | "security" | "build" | "test" | "state" | "agent" | "network" | "typecheck" | "lint" | "cluster" | "trace" | "runtime" | "render" | "backend" | "performance" | "deps";
|
|
79
|
+
severity: "error" | "info" | "warning" | "debug" | "fatal";
|
|
80
80
|
title: string;
|
|
81
81
|
kind: string | undefined;
|
|
82
82
|
area: FlowArea;
|
|
@@ -148,9 +148,9 @@ export declare function buildFlowDetail(rawEvents: BaseEvent[], opts?: FlowShape
|
|
|
148
148
|
outcome?: "returned" | "threw" | undefined;
|
|
149
149
|
calleeRequestId?: string | undefined;
|
|
150
150
|
hop?: true | undefined;
|
|
151
|
-
source: "
|
|
152
|
-
category: "
|
|
153
|
-
severity: "error" | "
|
|
151
|
+
source: "gateway" | "ai" | "db" | "redis" | "queue" | "external" | "visual" | "react" | "memory" | "nx" | "vite" | "typescript" | "eslint" | "rollup" | "client-runtime" | "chrome" | "valtio" | "nestjs" | "nextjs" | "perf" | "security" | "lens" | "custom";
|
|
152
|
+
category: "ai" | "db" | "visual" | "memory" | "security" | "build" | "test" | "state" | "agent" | "network" | "typecheck" | "lint" | "cluster" | "trace" | "runtime" | "render" | "backend" | "performance" | "deps";
|
|
153
|
+
severity: "error" | "info" | "warning" | "debug" | "fatal";
|
|
154
154
|
title: string;
|
|
155
155
|
kind: string | undefined;
|
|
156
156
|
area: FlowArea;
|
package/lib/patterns.d.ts
CHANGED
|
@@ -28,7 +28,17 @@ export interface DbInLoopOptions {
|
|
|
28
28
|
threshold?: number;
|
|
29
29
|
}
|
|
30
30
|
/**
|
|
31
|
-
*
|
|
31
|
+
* The DB calls a loop is judged by (`dbInLoop`): all it made — or, for a loop of a stream that says how many fell within
|
|
32
|
+
* two neighbouring seconds (`dbBurst`), those. A stream's pump reads every few seconds for as long as the stream is open:
|
|
33
|
+
* only a burst inside it is a loop's work (issues/closed/foodguard-148).
|
|
34
|
+
*/
|
|
35
|
+
export declare function loopDbCalls(loop: {
|
|
36
|
+
dbCallsInsideLoop?: unknown;
|
|
37
|
+
dbBurst?: unknown;
|
|
38
|
+
stream?: unknown;
|
|
39
|
+
}): number;
|
|
40
|
+
/**
|
|
41
|
+
* Flag `loop` events whose DB calls (`loopDbCalls`) exceed the threshold.
|
|
32
42
|
* Events are expected to carry `raw.kind === 'loop'` with a `loop`
|
|
33
43
|
* attribute matching `LoopAttrs`.
|
|
34
44
|
*/
|
package/lib/patterns.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var g=Object.defineProperty;var l=(n,o)=>g(n,"name",{value:o,configurable:!0});var y=Object.defineProperty,p=l((n,o)=>y(n,"name",{value:o,configurable:!0}),"l");export function loopDbCalls(n){const o=typeof n.dbCallsInsideLoop=="number"?n.dbCallsInsideLoop:0;return n.stream===!0&&typeof n.dbBurst=="number"?Math.min(o,n.dbBurst):o}l(loopDbCalls,"loopDbCalls"),p(loopDbCalls,"loopDbCalls");export function detectDbInLoop(n,o={}){const a=o.threshold??5,d=[];for(const t of n){const e=t.raw??null;if(e?.kind!=="loop"||!e.loop)continue;const i=loopDbCalls(e.loop);if(i>a){const r=e.loop.dbCallsInsideLoop??0,s=i<r;d.push({kind:"db-in-loop",severity:"warning",title:s?`${i} DB calls within two seconds of a stream's loop (${r} over its life)`:`${i} DB calls inside a loop (${e.loop.iterations??"?"} iterations)`,evidence:[t.id],details:{dbCallsInsideLoop:r,...s?{dbBurst:i,stream:!0}:{},iterations:e.loop.iterations,durationMs:e.loop.durationMs,threshold:a},detectedAt:t.timestamp})}}return d}l(detectDbInLoop,"detectDbInLoop"),p(detectDbInLoop,"detectDbInLoop");const I=new Set(["egress","db-query","redis-op","ai-call"]);function M(n){const o=n.raw??null;if(!o||typeof o.kind!="string"||!I.has(o.kind))return;const a=typeof o.durationMs=="number"?o.durationMs:void 0;if(a===void 0)return;const d=typeof o.startedAt=="number"?o.startedAt:n.timestamp-a,t=n.context??{};return{id:n.id,start:d,end:d+a,label:n.title,...typeof t.requestId=="string"?{requestId:t.requestId}:{},...typeof o.project=="string"?{project:o.project}:typeof t.projectName=="string"?{project:t.projectName}:{}}}l(M,"M"),p(M,"timedCall");function w(n){const o=n.raw??null,a=o?.kind==="span"?o.span:void 0;if(!a||typeof a.name!="string"||a.name.startsWith("nest.request "))return;const d=typeof a.durationMs=="number"?a.durationMs:void 0;if(d===void 0||d<=0)return;const t=typeof a.startTime=="number"?a.startTime:n.timestamp-d,e=n.context??{};return{id:n.id,start:t,end:t+d,label:a.name,...typeof e.requestId=="string"?{requestId:e.requestId}:{},...typeof o?.project=="string"?{project:o.project}:typeof e.projectName=="string"?{project:e.projectName}:{}}}l(w,"g"),p(w,"timedSpan");export function abandonedAwaitOf(n,o,a={}){const d=a.thresholdMs??250,t=M(n);if(!t||!t.requestId||t.end-t.start<d)return;let e;for(const r of o){const s=w(r);!s||s.requestId!==t.requestId||s.project!==void 0&&t.project!==void 0&&s.project!==t.project||s.start>t.start||s.end<=t.start||(!e||s.start>e.start||s.start===e.start&&s.end<e.end)&&(e=s)}if(!e)return;const i=Math.round(t.end-e.end);if(!(i<d))return{kind:"abandoned-await",severity:"warning",title:`${e.label} ended ${i}ms before a call it started had finished (${t.label})`,evidence:[e.id,t.id],details:{span:e.label,call:t.label,ranOnMs:i,spanMs:Math.round(e.end-e.start),callMs:Math.round(t.end-t.start),thresholdMs:d,...t.project?{project:t.project}:{}},detectedAt:n.timestamp}}l(abandonedAwaitOf,"abandonedAwaitOf"),p(abandonedAwaitOf,"abandonedAwaitOf");export function detectAbandonedAwait(n,o={}){const a=[];for(const d of n){const t=abandonedAwaitOf(d,n,o);t&&a.push(t)}return a}l(detectAbandonedAwait,"detectAbandonedAwait"),p(detectAbandonedAwait,"detectAbandonedAwait");export function detectNPlusOne(n,o={}){const a=o.threshold??3,d=new Map;for(const e of n){const i=e.raw??null;if(i?.kind!=="db-query"||!i.query?.signature)continue;const r=i.query.signature;let s=d.get(r);s||(s=[],d.set(r,s)),s.push(e)}const t=[];for(const[e,i]of d)i.length>=a&&t.push({kind:"n+1-query",severity:"warning",title:`Query repeated ${i.length}\xD7 \u2014 likely N+1`,evidence:i.map(r=>r.id),details:{signature:e,count:i.length,threshold:a},detectedAt:i[i.length-1].timestamp});return t}l(detectNPlusOne,"detectNPlusOne"),p(detectNPlusOne,"detectNPlusOne");export function detectRenderStorm(n,o={}){const a=o.threshold??5,d=o.windowMs??250,t=new Map;for(const i of n){if(i.source!=="react")continue;const r=i.raw??null;if(r?.kind!=="render"||!r.render?.componentInstanceId)continue;const s=r.render.componentInstanceId;let c=t.get(s);c||(c=[],t.set(s,c)),c.push(i)}const e=[];for(const[i,r]of t){r.sort((c,f)=>c.timestamp-f.timestamp);let s=0;for(let c=0;c<r.length;c++){for(;r[c].timestamp-r[s].timestamp>d;)s++;const f=c-s+1;if(f>a){const u=r.slice(s,c+1),m=u[0].raw.render?.componentName??i;e.push({kind:"render-storm",severity:"warning",title:`${m} rendered ${f}\xD7 in ${d}ms`,evidence:u.map(h=>h.id),details:{componentInstanceId:i,count:f,windowMs:d,threshold:a},detectedAt:u[u.length-1].timestamp});break}}}return e}l(detectRenderStorm,"detectRenderStorm"),p(detectRenderStorm,"detectRenderStorm");export function findSlowPath(n,o,a){const d=new Map,t=new Set;function e(r){const s=d.get(r);if(s)return s;if(t.has(r))return{path:[r],totalDurationMs:a(r)};t.add(r);const c=a(r),f=o.get(r)??[];let u;for(const h of f){const b=e(h);(!u||b.totalDurationMs>u.totalDurationMs)&&(u=b)}t.delete(r);const m=u?{path:[r,...u.path],totalDurationMs:c+u.totalDurationMs}:{path:[r],totalDurationMs:c};return d.set(r,m),m}l(e,"e"),p(e,"best");let i={path:[],totalDurationMs:0};for(const r of n){const s=e(r);s.totalDurationMs>i.totalDurationMs&&(i=s)}return i}l(findSlowPath,"findSlowPath"),p(findSlowPath,"findSlowPath");
|
|
@@ -11,8 +11,9 @@ import { type LensmcpThresholds } from './thresholds.js';
|
|
|
11
11
|
* The rules are the lens's own, so the gate and the dashboard never disagree about what is slow:
|
|
12
12
|
* - a route, a statement or a page is slow when it ran at or above its limit MORE THAN ONCE (the perf reducer's rule —
|
|
13
13
|
* a one-off spike, the first call after a rebuild, is not a breach; it is still in the numbers);
|
|
14
|
-
* - N+1: one request ran the same statement `nPlusOne` times or more
|
|
15
|
-
*
|
|
14
|
+
* - N+1: one request ran the same statement `nPlusOne` times or more — a streaming one, within one burst: its reads
|
|
15
|
+
* seconds apart are a stream's periodic work over its life, not a loop (issues/closed/foodguard-147);
|
|
16
|
+
* - DB in a loop: more than `dbInLoop` DB calls inside one loop — a stream's loop, within two seconds (`loopDbCalls`).
|
|
16
17
|
* A streaming response's time is how long it stayed open, not how slow it was: it is counted, never timed. A page the dev
|
|
17
18
|
* server reloaded (`cause: 'hmr'`) is left out, and a hard load is timed from the app's entry (`appReadyMs`), not from
|
|
18
19
|
* the dev server serving it.
|
|
@@ -133,11 +134,13 @@ export declare class PerformanceWindow {
|
|
|
133
134
|
private readonly sql;
|
|
134
135
|
private readonly drops;
|
|
135
136
|
private readonly pages;
|
|
136
|
-
/** Per open request: its statements' runs, until its `server-request` closes it. */
|
|
137
|
+
/** Per open request: its statements' runs, and in which seconds, until its `server-request` closes it. */
|
|
137
138
|
private readonly open;
|
|
138
139
|
/** A request's route once its `server-request` is seen. */
|
|
139
140
|
private readonly routeOf;
|
|
140
|
-
/**
|
|
141
|
+
/** The requests whose `server-request` said they streamed: their statements are judged by burst. */
|
|
142
|
+
private readonly streams;
|
|
143
|
+
/** N+1 per route and statement: the worst count, and where — and how many of its requests were streams. */
|
|
141
144
|
private readonly repeated;
|
|
142
145
|
private readonly loops;
|
|
143
146
|
constructor(limits: PerformanceLimits, waivers?: readonly PerformanceWaiver[]);
|
|
@@ -153,7 +156,10 @@ export declare class PerformanceWindow {
|
|
|
153
156
|
* told apart.
|
|
154
157
|
*/
|
|
155
158
|
private dropped;
|
|
156
|
-
/**
|
|
159
|
+
/**
|
|
160
|
+
* A request ended (or the window did): its repeated statements become N+1 records — a stream's by its worst burst. A
|
|
161
|
+
* request not seen ending is judged as a request: what it was is not known (a stream says so only when it closes).
|
|
162
|
+
*/
|
|
157
163
|
private close;
|
|
158
164
|
private loop;
|
|
159
165
|
private page;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var L=Object.defineProperty;var v=(o,t)=>L(o,"name",{value:t,configurable:!0});var N=Object.defineProperty,f=v((o,t)=>N(o,"name",{value:t,configurable:!0}),"f");import{resolveThresholds as E}from"./thresholds.js";export const SQL_DROPS_KIND="db-dropped",PERFORMANCE_EVENT_KINDS=["server-request","db-query",SQL_DROPS_KIND,"loop","page-visit"];export function performanceLimits(...o){let t={};for(const r of o)r&&(t={...t,...I(r)});const e=E(t);return{slowRouteMs:e.slowRouteMs,slowQueryMs:e.slowQueryMs,nPlusOne:e.nPlusOne,dbInLoop:e.dbInLoop,slowPageMs:e.slowPageMs}}v(performanceLimits,"performanceLimits"),f(performanceLimits,"performanceLimits");function I(o){const t={};for(const[e,r]of Object.entries(o))typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[e]=r);return t}v(I,"S"),f(I,"resolveThresholdsOnly");const $=f(o=>o&&typeof o=="object"?o:{},"obj"),m=f(o=>typeof o=="string"&&o?o:void 0,"str"),c=f(o=>typeof o=="number"&&Number.isFinite(o)?o:void 0,"num"),Q=2e3,j=5e3,R=2e4,k=f(()=>({count:0,times:[],slow:0,max:0,evidence:[]}),"newTiming");function q(o,t,e,r){if(o.max=Math.max(o.max,t),t>=e&&(o.slow+=1,o.evidence.length<5&&o.evidence.push(r)),o.times.length<Q)o.times.push(t);else{let n=0;for(let a=1;a<o.times.length;a++)o.times[a]<o.times[n]&&(n=a);t>o.times[n]&&(o.times[n]=t)}}v(q,"v"),f(q,"time");function P(o,t){return o.length?o[Math.min(o.length-1,Math.floor(o.length*t))]:0}v(P,"P"),f(P,"percentile");function x(o){const t=[...o.times].sort((e,r)=>e-r);return{count:o.count,timed:o.times.length,p50Ms:Math.round(P(t,.5)),p95Ms:Math.round(P(t,.95)),maxMs:Math.round(o.max),slow:o.slow}}v(x,"k"),f(x,"timing");function b(o,t,e){return o.includes("*")?new RegExp(`^${o.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(t):e?t===o:t.includes(o)}v(b,"y"),f(b,"matches");export class PerformanceWindow{static{v(this,"PerformanceWindow")}static{f(this,"PerformanceWindow")}constructor(t,e=[]){this.events=0,this.from=1/0,this.to=0,this.routes=new Map,this.sql=new Map,this.drops={runs:0,slow:0,failed:0},this.pages=new Map,this.open=new Map,this.routeOf=new Map,this.repeated=new Map,this.loops=[],this.limits=t,this.waivers=e.filter(r=>typeof r?.why=="string"&&(r.route||r.sql||r.page))}add(t){const e=$(t.raw),r=e.kind;if(r!=="server-request"&&r!=="db-query"&&r!==SQL_DROPS_KIND&&r!=="loop"&&r!=="page-visit")return;this.events+=1,this.from=Math.min(this.from,t.timestamp),this.to=Math.max(this.to,t.timestamp);const n=$(t.context),a=m(n.projectName)??m(e.project),l=m(n.requestId);r==="server-request"?this.request(t,e,a,l):r==="db-query"?this.statement(t,e,a,l):r===SQL_DROPS_KIND?this.dropped(t,e,a):r==="loop"?this.loop(t,e,l):this.page(t,e)}request(t,e,r,n){const a=$(e.request),l=m(a.method)??"?",p=m(a.route)??"?",u=`${l} ${p}`;let h=this.routes.get(u);if(!h){if(this.routes.size>=j)return;h={...k(),method:l,route:p,...r?{project:r}:{},errors:0,streaming:0},this.routes.set(u,h)}h.count+=1;const d=c(a.status);d!==void 0&&d>=500&&(h.errors+=1);const g=c(a.durationMs);a.streaming===!0?h.streaming+=1:g!==void 0&&q(h,g,this.limits.slowRouteMs,t.id),n&&(this.routeOf.set(n,u),this.routeOf.size>R&&this.routeOf.delete(this.routeOf.keys().next().value),this.close(n))}sqlEntry(t,e,r){let n=this.sql.get(t);if(!n&&this.sql.size<j){n={...k(),failed:0,dropped:0};const a=m(e.sqlName),l=m(e.op),p=m(e.table);a&&(n.name=a),r&&(n.project=r),l&&(n.op=l),p&&(n.table=p),this.sql.set(t,n)}return n}statement(t,e,r,n){const a=m(e.statement)??m(e.query),l=m(e.sqlId)??a?.slice(0,300);if(!l)return;const p=1+Math.max(0,c(e.floodSuppressed)??0),u=this.sqlEntry(l,e,r);if(u){u.count+=p,!u.text&&a&&(u.text=a.slice(0,300)),e.error!==void 0&&e.error!==null&&(u.failed+=1);const g=c(e.durationMs);g!==void 0&&q(u,g,this.limits.slowQueryMs,t.id)}if(!n)return;let h=this.open.get(n);h||(this.open.size>=R&&this.close(this.open.keys().next().value),h=new Map,this.open.set(n,h));const d=h.get(l);d?d.n+=p:h.set(l,{n:p,first:t.id})}dropped(t,e,r){const n=c(e.slowMs)??-1/0,a=f((h,d)=>Math.max(this.limits.slowQueryMs<=n?Math.max(0,c(h.slow)??0):0,d>=this.limits.slowQueryMs?1:0),"slowOf"),l=Array.isArray(e.shapes)?e.shapes:[];for(const h of l){const d=$(h),g=m(d.sqlId),s=Math.max(0,c(d.runs)??0);if(!g||!s)continue;const i=Math.max(0,c(d.maxMs)??0),M=Math.max(0,c(d.failed)??0),y=a(d,i);this.drops.runs+=s,this.drops.slow+=y,this.drops.failed+=M;const w=this.sqlEntry(g,d,r);if(w){if(w.count+=s,w.dropped+=s,w.failed+=M,w.max=Math.max(w.max,i),!w.text){const O=m(d.query);O&&(w.text=O.slice(0,300))}y&&(w.slow+=y,w.evidence.length<5&&w.evidence.push(t.id))}}const p=$(e.overflow),u=Math.max(0,c(p.runs)??0);if(u){const h=Math.max(0,c(p.maxMs)??0);this.drops.runs+=u,this.drops.slow+=a(p,h),this.drops.failed+=Math.max(0,c(p.failed)??0)}}close(t){const e=this.open.get(t);if(!e)return;this.open.delete(t);const r=this.routeOf.get(t)??"a request with no route seen";for(const[n,{n:a,first:l}]of e){if(a<this.limits.nPlusOne)continue;const p=`${r}\0${n}`,u=this.repeated.get(p)??{route:r,sql:n,worst:0,requests:0,evidence:[]};u.worst=Math.max(u.worst,a),u.requests+=1,u.evidence.length<5&&u.evidence.push(l),this.repeated.set(p,u)}}loop(t,e,r){const n=$(e.loop),a=c(n.dbCallsInsideLoop)??0;if(a<=this.limits.dbInLoop)return;const l=(r&&this.routeOf.get(r))??t.title??"a loop";this.loops.length>=200||this.loops.push({id:`db-in-loop:${l}`,kind:"db-in-loop",subject:l,measured:`${a} DB calls inside one loop (${c(n.iterations)??"?"} iterations)`,limit:`more than ${this.limits.dbInLoop} (dbInLoop)`,evidence:[t.id]})}page(t,e){if(e.phase!=="ready"||e.cause==="hmr")return;const r=m(e.app)??"?",n=m(e.pattern)??m(e.path)??"?",a=`${r} ${n}`;let l=this.pages.get(a);if(!l){if(this.pages.size>=j)return;l={...k(),app:r,path:n},this.pages.set(a,l)}l.count+=1;const p=e.nav==="hard"?c(e.appReadyMs)??c(e.readyMs):c(e.readyMs);p!==void 0&&q(l,p,this.limits.slowPageMs,t.id)}waiverOf(t){for(const e of this.waivers)if(e.route&&t.route&&b(e.route,t.route,!0)||e.sql&&t.sql&&(b(e.sql,t.sql,!1)||t.sqlText!==void 0&&b(e.sql,t.sqlText,!1))||e.page&&t.page&&b(e.page,t.page,!0))return e.why}report(t){for(const s of[...this.open.keys()])this.close(s);const e=this.limits,r=[],n=f((s,i="runs")=>`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.timed} ${i} at or above`,"slowWords"),a=[...this.routes.entries()].map(([s,i])=>({key:s,method:i.method,route:i.route,...i.project?{project:i.project}:{},errors:i.errors,streaming:i.streaming,...x(i),evidence:i.evidence}));for(const s of a)s.slow>1&&r.push({breach:{id:`slow-route:${s.key}`,kind:"slow-route",subject:s.key,measured:n(s),limit:`${e.slowRouteMs} ms (slowRouteMs)`,evidence:s.evidence},about:{route:s.key}});const l=[...this.sql.entries()].map(([s,i])=>({key:s,...i.name?{name:i.name}:{},...i.project?{project:i.project}:{},...i.op?{op:i.op}:{},...i.table?{table:i.table}:{},...i.text?{text:i.text}:{},failed:i.failed,...i.dropped?{dropped:i.dropped}:{},...x(i),evidence:i.evidence}));for(const s of l){const i=s.dropped?`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.count} runs at or above (${s.dropped} counted from the service's drop record, not timed)`:n(s);s.slow>1&&r.push({breach:{id:`slow-query:${s.key}`,kind:"slow-query",subject:s.name??s.key,measured:i,limit:`${e.slowQueryMs} ms (slowQueryMs)`,evidence:s.evidence},about:{sql:s.key,...s.text?{sqlText:s.text}:{}}})}for(const s of this.repeated.values()){const i=this.sql.get(s.sql);r.push({breach:{id:`n+1-query:${s.route}:${s.sql}`,kind:"n+1-query",subject:`${s.route} runs ${i?.name??s.sql}`,measured:`up to ${s.worst}\xD7 in one request (${s.requests} request${s.requests===1?"":"s"})`,limit:`fewer than ${e.nPlusOne} (nPlusOne)`,evidence:s.evidence},about:{route:s.route,sql:s.sql,...i?.text?{sqlText:i.text}:{}}})}for(const s of this.loops)r.push({breach:s,about:{route:s.subject}});const p=[...this.pages.entries()].map(([s,i])=>({key:s,app:i.app,path:i.path,...x(i),evidence:i.evidence}));for(const s of p)s.slow>1&&r.push({breach:{id:`slow-page:${s.key}`,kind:"slow-page",subject:s.key,measured:n(s,"visits"),limit:`${e.slowPageMs} ms (slowPageMs)`,evidence:s.evidence},about:{page:s.path}});const u=[],h=[];for(const{breach:s,about:i}of r){const M=this.waiverOf(i);M?h.push({...s,waived:M}):u.push(s)}const d=f(s=>{const{evidence:i,...M}=s;return M},"strip"),g=this.routes.size+this.sql.size+this.pages.size+this.drops.runs>0;return{window:t??{from:Number.isFinite(this.from)?this.from:0,to:this.to},events:this.events,limits:{...e},verdict:u.length?"fail":g?"pass":"unmeasured",breaches:u,waived:h,...this.drops.runs?{dropped:{...this.drops}}:{},routes:a.map(d).sort((s,i)=>i.p95Ms-s.p95Ms),sql:l.map(d).sort((s,i)=>i.p95Ms-s.p95Ms),pages:p.map(d).sort((s,i)=>i.p95Ms-s.p95Ms)}}}export function describePerformance(o,t=12){const e=o.limits,r=[o.verdict==="unmeasured"?"Performance: unmeasured \u2014 no request, statement or page ran in the window.":`Performance: ${o.verdict==="pass"?"PASS":`FAIL \u2014 ${o.breaches.length} breach${o.breaches.length===1?"":"es"}`} over ${o.routes.length} route${o.routes.length===1?"":"s"}, ${o.sql.length} statement${o.sql.length===1?"":"s"}, ${o.pages.length} page${o.pages.length===1?"":"s"} (limits: route ${e.slowRouteMs} ms, query ${e.slowQueryMs} ms, N+1 ${e.nPlusOne}, DB in a loop ${e.dbInLoop}, page ${e.slowPageMs} ms).`],n=o.dropped;n&&r.push(`${n.runs} statement run${n.runs===1?"":"s"} reached the lens only as counts (the services' flood guards): ${n.slow} slow, ${n.failed} failed \u2014 counted above, not in the percentiles.`);for(const a of o.breaches.slice(0,t))r.push(`- ${a.kind} \xB7 ${a.subject}: ${a.measured}; limit ${a.limit}`);return o.breaches.length>t&&r.push(`- \u2026 ${o.breaches.length-t} more`),o.waived.length&&r.push(`Waived by .lensmcp/team/performance.json: ${o.waived.map(a=>`${a.kind} \xB7 ${a.subject} (${a.waived})`).slice(0,t).join("; ")}`),r.join(`
|
|
1
|
+
"use strict";var z=Object.defineProperty;var v=(o,t)=>z(o,"name",{value:t,configurable:!0});var N=Object.defineProperty,f=v((o,t)=>N(o,"name",{value:t,configurable:!0}),"f");import{loopDbCalls as D}from"./patterns.js";import{resolveThresholds as E}from"./thresholds.js";export const SQL_DROPS_KIND="db-dropped",PERFORMANCE_EVENT_KINDS=["server-request","db-query",SQL_DROPS_KIND,"loop","page-visit"];export function performanceLimits(...o){let t={};for(const r of o)r&&(t={...t,...L(r)});const e=E(t);return{slowRouteMs:e.slowRouteMs,slowQueryMs:e.slowQueryMs,nPlusOne:e.nPlusOne,dbInLoop:e.dbInLoop,slowPageMs:e.slowPageMs}}v(performanceLimits,"performanceLimits"),f(performanceLimits,"performanceLimits");function L(o){const t={};for(const[e,r]of Object.entries(o))typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[e]=r);return t}v(L,"E"),f(L,"resolveThresholdsOnly");const $=f(o=>o&&typeof o=="object"?o:{},"obj"),w=f(o=>typeof o=="string"&&o?o:void 0,"str"),m=f(o=>typeof o=="number"&&Number.isFinite(o)?o:void 0,"num"),Q=2e3,j=5e3,k=2e4,T=1e3,S=1024;function R(o){let t=0;for(const[e,r]of o)t=Math.max(t,r+(o.get(e+1)??0));return t}v(R,"L"),f(R,"burstOf");const O=f(()=>({count:0,times:[],slow:0,max:0,evidence:[]}),"newTiming");function q(o,t,e,r){if(o.max=Math.max(o.max,t),t>=e&&(o.slow+=1,o.evidence.length<5&&o.evidence.push(r)),o.times.length<Q)o.times.push(t);else{let a=0;for(let n=1;n<o.times.length;n++)o.times[n]<o.times[a]&&(a=n);t>o.times[a]&&(o.times[a]=t)}}v(q,"k"),f(q,"time");function P(o,t){return o.length?o[Math.min(o.length-1,Math.floor(o.length*t))]:0}v(P,"P"),f(P,"percentile");function x(o){const t=[...o.times].sort((e,r)=>e-r);return{count:o.count,timed:o.times.length,p50Ms:Math.round(P(t,.5)),p95Ms:Math.round(P(t,.95)),maxMs:Math.round(o.max),slow:o.slow}}v(x,"j"),f(x,"timing");function b(o,t,e){return o.includes("*")?new RegExp(`^${o.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(t):e?t===o:t.includes(o)}v(b,"y"),f(b,"matches");export class PerformanceWindow{static{v(this,"PerformanceWindow")}static{f(this,"PerformanceWindow")}constructor(t,e=[]){this.events=0,this.from=1/0,this.to=0,this.routes=new Map,this.sql=new Map,this.drops={runs:0,slow:0,failed:0},this.pages=new Map,this.open=new Map,this.routeOf=new Map,this.streams=new Set,this.repeated=new Map,this.loops=[],this.limits=t,this.waivers=e.filter(r=>typeof r?.why=="string"&&(r.route||r.sql||r.page))}add(t){const e=$(t.raw),r=e.kind;if(r!=="server-request"&&r!=="db-query"&&r!==SQL_DROPS_KIND&&r!=="loop"&&r!=="page-visit")return;this.events+=1,this.from=Math.min(this.from,t.timestamp),this.to=Math.max(this.to,t.timestamp);const a=$(t.context),n=w(a.projectName)??w(e.project),l=w(a.requestId);r==="server-request"?this.request(t,e,n,l):r==="db-query"?this.statement(t,e,n,l):r===SQL_DROPS_KIND?this.dropped(t,e,n):r==="loop"?this.loop(t,e,l):this.page(t,e)}request(t,e,r,a){const n=$(e.request),l=w(n.method)??"?",u=w(n.route)??"?",d=`${l} ${u}`;let h=this.routes.get(d);if(!h){if(this.routes.size>=j)return;h={...O(),method:l,route:u,...r?{project:r}:{},errors:0,streaming:0},this.routes.set(d,h)}h.count+=1;const p=m(n.status);p!==void 0&&p>=500&&(h.errors+=1);const c=m(n.durationMs);n.streaming===!0?h.streaming+=1:c!==void 0&&q(h,c,this.limits.slowRouteMs,t.id),a&&(this.routeOf.set(a,d),this.routeOf.size>k&&this.routeOf.delete(this.routeOf.keys().next().value),n.streaming===!0&&(this.streams.add(a),this.streams.size>k&&this.streams.delete(this.streams.keys().next().value)),this.close(a))}sqlEntry(t,e,r){let a=this.sql.get(t);if(!a&&this.sql.size<j){a={...O(),failed:0,dropped:0};const n=w(e.sqlName),l=w(e.op),u=w(e.table);n&&(a.name=n),r&&(a.project=r),l&&(a.op=l),u&&(a.table=u),this.sql.set(t,a)}return a}statement(t,e,r,a){const n=w(e.statement)??w(e.query),l=w(e.sqlId)??n?.slice(0,300);if(!l)return;const u=1+Math.max(0,m(e.floodSuppressed)??0),d=this.sqlEntry(l,e,r);if(d){d.count+=u,!d.text&&n&&(d.text=n.slice(0,300)),e.error!==void 0&&e.error!==null&&(d.failed+=1);const i=m(e.durationMs);i!==void 0&&q(d,i,this.limits.slowQueryMs,t.id)}if(!a)return;let h=this.open.get(a);h||(this.open.size>=k&&this.close(this.open.keys().next().value),h=new Map,this.open.set(a,h));let p=h.get(l);p?p.n+=u:h.set(l,p={n:u,first:t.id,seconds:new Map});const c=Math.floor(t.timestamp/T),s=p.seconds.get(c);s!==void 0?p.seconds.set(c,s+u):p.seconds.size<S&&p.seconds.set(c,u)}dropped(t,e,r){const a=m(e.slowMs)??-1/0,n=f((h,p)=>Math.max(this.limits.slowQueryMs<=a?Math.max(0,m(h.slow)??0):0,p>=this.limits.slowQueryMs?1:0),"slowOf"),l=Array.isArray(e.shapes)?e.shapes:[];for(const h of l){const p=$(h),c=w(p.sqlId),s=Math.max(0,m(p.runs)??0);if(!c||!s)continue;const i=Math.max(0,m(p.maxMs)??0),M=Math.max(0,m(p.failed)??0),y=n(p,i);this.drops.runs+=s,this.drops.slow+=y,this.drops.failed+=M;const g=this.sqlEntry(c,p,r);if(g){if(g.count+=s,g.dropped+=s,g.failed+=M,g.max=Math.max(g.max,i),!g.text){const I=w(p.query);I&&(g.text=I.slice(0,300))}y&&(g.slow+=y,g.evidence.length<5&&g.evidence.push(t.id))}}const u=$(e.overflow),d=Math.max(0,m(u.runs)??0);if(d){const h=Math.max(0,m(u.maxMs)??0);this.drops.runs+=d,this.drops.slow+=n(u,h),this.drops.failed+=Math.max(0,m(u.failed)??0)}}close(t){const e=this.open.get(t);if(!e)return;this.open.delete(t);const r=this.routeOf.get(t)??"a request with no route seen",a=this.streams.delete(t);for(const[n,{n:l,first:u,seconds:d}]of e){const h=a?R(d):l;if(h<this.limits.nPlusOne)continue;const p=`${r}\0${n}`,c=this.repeated.get(p)??{route:r,sql:n,worst:0,requests:0,streams:0,evidence:[]};c.worst=Math.max(c.worst,h),c.requests+=1,a&&(c.streams+=1),c.evidence.length<5&&c.evidence.push(u),this.repeated.set(p,c)}}loop(t,e,r){const a=$(e.loop),n=D(a);if(n<=this.limits.dbInLoop)return;const l=m(a.dbCallsInsideLoop)??0,u=(r&&this.routeOf.get(r))??t.title??"a loop";this.loops.length>=200||this.loops.push({id:`db-in-loop:${u}`,kind:"db-in-loop",subject:u,measured:n<l?`${n} DB calls within two seconds of one loop of a stream (${l} over its life)`:`${n} DB calls inside one loop (${m(a.iterations)??"?"} iterations)`,limit:`more than ${this.limits.dbInLoop} (dbInLoop)`,evidence:[t.id]})}page(t,e){if(e.phase!=="ready"||e.cause==="hmr")return;const r=w(e.app)??"?",a=w(e.pattern)??w(e.path)??"?",n=`${r} ${a}`;let l=this.pages.get(n);if(!l){if(this.pages.size>=j)return;l={...O(),app:r,path:a},this.pages.set(n,l)}l.count+=1;const u=e.nav==="hard"?m(e.appReadyMs)??m(e.readyMs):m(e.readyMs);u!==void 0&&q(l,u,this.limits.slowPageMs,t.id)}waiverOf(t){for(const e of this.waivers)if(e.route&&t.route&&b(e.route,t.route,!0)||e.sql&&t.sql&&(b(e.sql,t.sql,!1)||t.sqlText!==void 0&&b(e.sql,t.sqlText,!1))||e.page&&t.page&&b(e.page,t.page,!0))return e.why}report(t){for(const s of[...this.open.keys()])this.close(s);const e=this.limits,r=[],a=f((s,i="runs")=>`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.timed} ${i} at or above`,"slowWords"),n=[...this.routes.entries()].map(([s,i])=>({key:s,method:i.method,route:i.route,...i.project?{project:i.project}:{},errors:i.errors,streaming:i.streaming,...x(i),evidence:i.evidence}));for(const s of n)s.slow>1&&r.push({breach:{id:`slow-route:${s.key}`,kind:"slow-route",subject:s.key,measured:a(s),limit:`${e.slowRouteMs} ms (slowRouteMs)`,evidence:s.evidence},about:{route:s.key}});const l=[...this.sql.entries()].map(([s,i])=>({key:s,...i.name?{name:i.name}:{},...i.project?{project:i.project}:{},...i.op?{op:i.op}:{},...i.table?{table:i.table}:{},...i.text?{text:i.text}:{},failed:i.failed,...i.dropped?{dropped:i.dropped}:{},...x(i),evidence:i.evidence}));for(const s of l){const i=s.dropped?`p95 ${s.p95Ms} ms, max ${s.maxMs} ms \u2014 ${s.slow} of ${s.count} runs at or above (${s.dropped} counted from the service's drop record, not timed)`:a(s);s.slow>1&&r.push({breach:{id:`slow-query:${s.key}`,kind:"slow-query",subject:s.name??s.key,measured:i,limit:`${e.slowQueryMs} ms (slowQueryMs)`,evidence:s.evidence},about:{sql:s.key,...s.text?{sqlText:s.text}:{}}})}for(const s of this.repeated.values()){const i=this.sql.get(s.sql);r.push({breach:{id:`n+1-query:${s.route}:${s.sql}`,kind:"n+1-query",subject:`${s.route} runs ${i?.name??s.sql}`,measured:s.streams===s.requests?`up to ${s.worst}\xD7 in one burst of a stream, within two seconds (${s.streams} stream${s.streams===1?"":"s"})`:`up to ${s.worst}\xD7 in one request (${s.requests} request${s.requests===1?"":"s"})`,limit:`fewer than ${e.nPlusOne} (nPlusOne)`,evidence:s.evidence},about:{route:s.route,sql:s.sql,...i?.text?{sqlText:i.text}:{}}})}for(const s of this.loops)r.push({breach:s,about:{route:s.subject}});const u=[...this.pages.entries()].map(([s,i])=>({key:s,app:i.app,path:i.path,...x(i),evidence:i.evidence}));for(const s of u)s.slow>1&&r.push({breach:{id:`slow-page:${s.key}`,kind:"slow-page",subject:s.key,measured:a(s,"visits"),limit:`${e.slowPageMs} ms (slowPageMs)`,evidence:s.evidence},about:{page:s.path}});const d=[],h=[];for(const{breach:s,about:i}of r){const M=this.waiverOf(i);M?h.push({...s,waived:M}):d.push(s)}const p=f(s=>{const{evidence:i,...M}=s;return M},"strip"),c=this.routes.size+this.sql.size+this.pages.size+this.drops.runs>0;return{window:t??{from:Number.isFinite(this.from)?this.from:0,to:this.to},events:this.events,limits:{...e},verdict:d.length?"fail":c?"pass":"unmeasured",breaches:d,waived:h,...this.drops.runs?{dropped:{...this.drops}}:{},routes:n.map(p).sort((s,i)=>i.p95Ms-s.p95Ms),sql:l.map(p).sort((s,i)=>i.p95Ms-s.p95Ms),pages:u.map(p).sort((s,i)=>i.p95Ms-s.p95Ms)}}}export function describePerformance(o,t=12){const e=o.limits,r=[o.verdict==="unmeasured"?"Performance: unmeasured \u2014 no request, statement or page ran in the window.":`Performance: ${o.verdict==="pass"?"PASS":`FAIL \u2014 ${o.breaches.length} breach${o.breaches.length===1?"":"es"}`} over ${o.routes.length} route${o.routes.length===1?"":"s"}, ${o.sql.length} statement${o.sql.length===1?"":"s"}, ${o.pages.length} page${o.pages.length===1?"":"s"} (limits: route ${e.slowRouteMs} ms, query ${e.slowQueryMs} ms, N+1 ${e.nPlusOne}, DB in a loop ${e.dbInLoop}, page ${e.slowPageMs} ms).`],a=o.dropped;a&&r.push(`${a.runs} statement run${a.runs===1?"":"s"} reached the lens only as counts (the services' flood guards): ${a.slow} slow, ${a.failed} failed \u2014 counted above, not in the percentiles.`);for(const n of o.breaches.slice(0,t))r.push(`- ${n.kind} \xB7 ${n.subject}: ${n.measured}; limit ${n.limit}`);return o.breaches.length>t&&r.push(`- \u2026 ${o.breaches.length-t} more`),o.waived.length&&r.push(`Waived by .lensmcp/team/performance.json: ${o.waived.map(n=>`${n.kind} \xB7 ${n.subject} (${n.waived})`).slice(0,t).join("; ")}`),r.join(`
|
|
2
2
|
`)}v(describePerformance,"describePerformance"),f(describePerformance,"describePerformance");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lensmcp/core",
|
|
3
|
-
"version": "1.25.
|
|
3
|
+
"version": "1.25.46",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"module": "./index.js",
|
|
@@ -84,7 +84,7 @@
|
|
|
84
84
|
}
|
|
85
85
|
},
|
|
86
86
|
"dependencies": {
|
|
87
|
-
"@lensmcp/protocol-types": "1.25.
|
|
87
|
+
"@lensmcp/protocol-types": "1.25.46",
|
|
88
88
|
"tslib": "^2.3.0"
|
|
89
89
|
},
|
|
90
90
|
"license": "Apache-2.0",
|