dsh-context-compression-improved 0.8.0-beta.2 → 0.8.0-beta.3

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.
@@ -1,188 +1,192 @@
1
- /**
2
- * Host-side guard for the estimator catalog route.
3
- *
4
- * The defect this pins is a registration that never happens: the injection gate
5
- * asked for more services than the handler needs, and an unsatisfied
6
- * `ctx.inject` callback fails silently, so the plugin simply had no HTTP API
7
- * and every request fell through to the host 404. These cases assert the two
8
- * properties that failure violated — the route appears whenever `webServer` is
9
- * usable, in either arrival order, and its absence is never silent.
10
- */
11
-
12
- import { Context } from '@deepseek-ai/cordis'
13
- import { afterEach, describe, expect, it, vi } from 'vitest'
14
- import { apply } from '../src/index.ts'
15
-
16
- const CATALOG_ROUTE = '/api/dsh-context-compression-improved/estimator-catalog'
17
- const LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/estimator-catalog'
18
-
19
- interface RegisteredRoute {
20
- kind: string
21
- path: string
22
- handler: (req: unknown, res: unknown) => void
23
- }
24
-
25
- interface FakeResponse {
26
- status?: number
27
- body?: string
28
- }
29
-
30
- /** The state `register` reads off its own `this`, mirroring the host service. */
31
- interface WebServerStub {
32
- tables: { exact: Map<string, RegisteredRoute> }
33
- }
34
-
35
- let ctx: Context | undefined
36
-
37
- afterEach(async () => {
38
- await ctx?.fiber.dispose()
39
- ctx = undefined
40
- })
41
-
42
- /** Settle one macrotask so a deferred activation callback can run. */
43
- const settle = (): Promise<void> => new Promise(resolve => setTimeout(resolve, 20))
44
-
45
- /**
46
- * Mount a host web server stand-in that records routes and reproduces the real
47
- * host's duplicate-`(kind, path)` contract, so a double registration is a
48
- * failure rather than a silent overwrite.
49
- */
50
- async function mountWebServer(runtime: Context, routes: RegisteredRoute[]): Promise<void> {
51
- await runtime.plugin({
52
- name: 'fake-webserver',
53
- apply(webCtx) {
54
- webCtx.provide('webServer', {
55
- // Mirrors dsh-host-webserver: `register` reads its route table off
56
- // `this`. A caller that detaches the method and invokes it standalone
57
- // makes `this` the wrapper and fails here, exactly as the host does --
58
- // which is the defect this spec exists to catch.
59
- tables: { exact: new Map<string, RegisteredRoute>() },
60
- register(this: WebServerStub, route: RegisteredRoute) {
61
- const table = this.tables.exact
62
- if (table.has(route.path)) {
63
- throw new Error(`webserver: duplicate ${route.kind} route "${route.path}"`)
64
- }
65
- table.set(route.path, route)
66
- routes.push(route)
67
- return () => {}
68
- },
69
- })
70
- },
71
- })
72
- }
73
-
74
- /** Mount the estimator-side services the handler only enriches its payload with. */
75
- async function mountEstimatorServices(runtime: Context): Promise<void> {
76
- await runtime.plugin({
77
- name: 'fake-estimator-services',
78
- apply(estimatorCtx) {
79
- estimatorCtx.provide('llm', { listProviders: () => [] })
80
- estimatorCtx.provide('agentDefaultModel', { currentSelection: () => undefined })
81
- },
82
- })
83
- }
84
-
85
- /** Drive one registered route through a stand-in response. */
86
- async function invoke(route: RegisteredRoute): Promise<FakeResponse> {
87
- const captured: FakeResponse = {}
88
- const res = {
89
- writeHead(code: number) { captured.status = code },
90
- end(body?: string) { if (body !== undefined) captured.body = body },
91
- }
92
- route.handler({ method: 'GET' }, res)
93
- await settle()
94
- return captured
95
- }
96
-
97
- describe('estimator catalog route registration', () => {
98
- it('registers both route prefixes with only webServer present', async () => {
99
- const routes: RegisteredRoute[] = []
100
- const runtime = new Context()
101
- ctx = runtime
102
- await mountWebServer(runtime, routes)
103
-
104
- apply(runtime, { estimatorCatalogRoute: true })
105
- await settle()
106
-
107
- expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE])
108
- expect(routes.every(route => route.kind === 'exact')).toBe(true)
109
- })
110
-
111
- it('registers the route when webServer activates after the plugin applied', async () => {
112
- const routes: RegisteredRoute[] = []
113
- const runtime = new Context()
114
- ctx = runtime
115
-
116
- apply(runtime, { estimatorCatalogRoute: true })
117
- await settle()
118
- expect(routes).toHaveLength(0)
119
-
120
- await mountWebServer(runtime, routes)
121
- await settle()
122
-
123
- expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE])
124
- })
125
-
126
- it('registers nothing twice when the estimator services arrive later', async () => {
127
- const routes: RegisteredRoute[] = []
128
- const runtime = new Context()
129
- ctx = runtime
130
- await mountWebServer(runtime, routes)
131
-
132
- apply(runtime, { estimatorCatalogRoute: true })
133
- await settle()
134
- const afterRegistration = routes.length
135
-
136
- await mountEstimatorServices(runtime)
137
- await settle()
138
-
139
- expect(routes).toHaveLength(afterRegistration)
140
- })
141
-
142
- it('keeps the rest of the plugin alive and warns when webServer never arrives', async () => {
143
- const runtime = new Context()
144
- ctx = runtime
145
- // The diagnostic goes to `console`: the host's cordis logger surfaces no
146
- // plugin output at all, so a lifecycle line published there is invisible.
147
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
148
-
149
- try {
150
- expect(() => apply(runtime, { estimatorCatalogRoute: true })).not.toThrow()
151
- await settle()
152
-
153
- const messages = warn.mock.calls.map(([message]) => String(message))
154
- expect(messages.some(message => message.includes('estimator catalog route pending'))).toBe(true)
155
- } finally {
156
- warn.mockRestore()
157
- }
158
- })
159
-
160
- it('answers 200 without the estimator services, which only enrich the payload', async () => {
161
- const routes: RegisteredRoute[] = []
162
- const runtime = new Context()
163
- ctx = runtime
164
- await mountWebServer(runtime, routes)
165
-
166
- apply(runtime, { estimatorCatalogRoute: true })
167
- await settle()
168
-
169
- const route = routes.find(candidate => candidate.path === CATALOG_ROUTE)
170
- expect(route).toBeDefined()
171
- const response = await invoke(route as RegisteredRoute)
172
-
173
- expect(response.status).toBe(200)
174
- expect(JSON.parse(String(response.body))).toMatchObject({ ok: true, providers: [] })
175
- })
176
-
177
- it('registers no route when the row does not opt in', async () => {
178
- const routes: RegisteredRoute[] = []
179
- const runtime = new Context()
180
- ctx = runtime
181
- await mountWebServer(runtime, routes)
182
-
183
- apply(runtime, { presetOverlay: false })
184
- await settle()
185
-
186
- expect(routes).toHaveLength(0)
187
- })
188
- })
1
+ /**
2
+ * Host-side guard for the estimator catalog route.
3
+ *
4
+ * The defect this pins is a registration that never happens: the injection gate
5
+ * asked for more services than the handler needs, and an unsatisfied
6
+ * `ctx.inject` callback fails silently, so the plugin simply had no HTTP API
7
+ * and every request fell through to the host 404. These cases assert the two
8
+ * properties that failure violated — the route appears whenever `webServer` is
9
+ * usable, in either arrival order, and its absence is never silent.
10
+ */
11
+
12
+ import { Context } from '@deepseek-ai/cordis'
13
+ import { afterEach, describe, expect, it, vi } from 'vitest'
14
+ import { apply } from '../src/index.ts'
15
+
16
+ const CATALOG_ROUTE = '/api/dsh-context-compression-improved/estimator-catalog'
17
+ const LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/estimator-catalog'
18
+ const SAVINGS_ROUTE = '/api/dsh-context-compression-improved/savings'
19
+ const SAVINGS_LEGACY_ROUTE = '/endpoint/dsh-context-compression-improved/savings'
20
+
21
+ interface RegisteredRoute {
22
+ kind: string
23
+ path: string
24
+ handler: (req: unknown, res: unknown) => void
25
+ }
26
+
27
+ interface FakeResponse {
28
+ status?: number
29
+ body?: string
30
+ }
31
+
32
+ /** The state `register` reads off its own `this`, mirroring the host service. */
33
+ interface WebServerStub {
34
+ tables: { exact: Map<string, RegisteredRoute> }
35
+ }
36
+
37
+ let ctx: Context | undefined
38
+
39
+ afterEach(async () => {
40
+ await ctx?.fiber.dispose()
41
+ ctx = undefined
42
+ })
43
+
44
+ /** Settle one macrotask so a deferred activation callback can run. */
45
+ const settle = (): Promise<void> => new Promise(resolve => setTimeout(resolve, 20))
46
+
47
+ /**
48
+ * Mount a host web server stand-in that records routes and reproduces the real
49
+ * host's duplicate-`(kind, path)` contract, so a double registration is a
50
+ * failure rather than a silent overwrite.
51
+ */
52
+ async function mountWebServer(runtime: Context, routes: RegisteredRoute[]): Promise<void> {
53
+ await runtime.plugin({
54
+ name: 'fake-webserver',
55
+ apply(webCtx) {
56
+ webCtx.provide('webServer', {
57
+ // Mirrors dsh-host-webserver: `register` reads its route table off
58
+ // `this`. A caller that detaches the method and invokes it standalone
59
+ // makes `this` the wrapper and fails here, exactly as the host does --
60
+ // which is the defect this spec exists to catch.
61
+ tables: { exact: new Map<string, RegisteredRoute>() },
62
+ register(this: WebServerStub, route: RegisteredRoute) {
63
+ const table = this.tables.exact
64
+ if (table.has(route.path)) {
65
+ throw new Error(`webserver: duplicate ${route.kind} route "${route.path}"`)
66
+ }
67
+ table.set(route.path, route)
68
+ routes.push(route)
69
+ return () => {}
70
+ },
71
+ })
72
+ },
73
+ })
74
+ }
75
+
76
+ /** Mount the estimator-side services the handler only enriches its payload with. */
77
+ async function mountEstimatorServices(runtime: Context): Promise<void> {
78
+ await runtime.plugin({
79
+ name: 'fake-estimator-services',
80
+ apply(estimatorCtx) {
81
+ estimatorCtx.provide('llm', { listProviders: () => [] })
82
+ estimatorCtx.provide('agentDefaultModel', { currentSelection: () => undefined })
83
+ },
84
+ })
85
+ }
86
+
87
+ /** Drive one registered route through a stand-in response. */
88
+ async function invoke(route: RegisteredRoute): Promise<FakeResponse> {
89
+ const captured: FakeResponse = {}
90
+ const res = {
91
+ writeHead(code: number) { captured.status = code },
92
+ end(body?: string) { if (body !== undefined) captured.body = body },
93
+ }
94
+ route.handler({ method: 'GET' }, res)
95
+ await settle()
96
+ return captured
97
+ }
98
+
99
+ describe('estimator catalog route registration', () => {
100
+ it('registers both route prefixes with only webServer present', async () => {
101
+ const routes: RegisteredRoute[] = []
102
+ const runtime = new Context()
103
+ ctx = runtime
104
+ await mountWebServer(runtime, routes)
105
+
106
+ apply(runtime, { estimatorCatalogRoute: true })
107
+ await settle()
108
+
109
+ expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
110
+ expect(routes.every(route => route.kind === 'exact')).toBe(true)
111
+ })
112
+
113
+ it('registers the route when webServer activates after the plugin applied', async () => {
114
+ const routes: RegisteredRoute[] = []
115
+ const runtime = new Context()
116
+ ctx = runtime
117
+
118
+ apply(runtime, { estimatorCatalogRoute: true })
119
+ await settle()
120
+ expect(routes).toHaveLength(0)
121
+
122
+ await mountWebServer(runtime, routes)
123
+ await settle()
124
+
125
+ expect(routes.map(route => route.path)).toEqual([LEGACY_ROUTE, CATALOG_ROUTE, SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
126
+ })
127
+
128
+ it('registers nothing twice when the estimator services arrive later', async () => {
129
+ const routes: RegisteredRoute[] = []
130
+ const runtime = new Context()
131
+ ctx = runtime
132
+ await mountWebServer(runtime, routes)
133
+
134
+ apply(runtime, { estimatorCatalogRoute: true })
135
+ await settle()
136
+ const afterRegistration = routes.length
137
+
138
+ await mountEstimatorServices(runtime)
139
+ await settle()
140
+
141
+ expect(routes).toHaveLength(afterRegistration)
142
+ })
143
+
144
+ it('keeps the rest of the plugin alive and warns when webServer never arrives', async () => {
145
+ const runtime = new Context()
146
+ ctx = runtime
147
+ // The diagnostic goes to `console`: the host's cordis logger surfaces no
148
+ // plugin output at all, so a lifecycle line published there is invisible.
149
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
150
+
151
+ try {
152
+ expect(() => apply(runtime, { estimatorCatalogRoute: true })).not.toThrow()
153
+ await settle()
154
+
155
+ const messages = warn.mock.calls.map(([message]) => String(message))
156
+ expect(messages.some(message => message.includes('estimator catalog route pending'))).toBe(true)
157
+ } finally {
158
+ warn.mockRestore()
159
+ }
160
+ })
161
+
162
+ it('answers 200 without the estimator services, which only enrich the payload', async () => {
163
+ const routes: RegisteredRoute[] = []
164
+ const runtime = new Context()
165
+ ctx = runtime
166
+ await mountWebServer(runtime, routes)
167
+
168
+ apply(runtime, { estimatorCatalogRoute: true })
169
+ await settle()
170
+
171
+ const route = routes.find(candidate => candidate.path === CATALOG_ROUTE)
172
+ expect(route).toBeDefined()
173
+ const response = await invoke(route as RegisteredRoute)
174
+
175
+ expect(response.status).toBe(200)
176
+ expect(JSON.parse(String(response.body))).toMatchObject({ ok: true, providers: [] })
177
+ })
178
+
179
+ it('without the estimator opt-in only the always-on savings snapshot route registers', async () => {
180
+ // savings 路由是有意常开的只读面(纯 token 聚合,无会话内容);estimator
181
+ // catalog 才是 opt-in 行。默认面 = 恰好两条 savings 前缀。
182
+ const routes: RegisteredRoute[] = []
183
+ const runtime = new Context()
184
+ ctx = runtime
185
+ await mountWebServer(runtime, routes)
186
+
187
+ apply(runtime, { presetOverlay: false })
188
+ await settle()
189
+
190
+ expect(routes.map(route => route.path)).toEqual([SAVINGS_LEGACY_ROUTE, SAVINGS_ROUTE])
191
+ })
192
+ })
@@ -0,0 +1,120 @@
1
+ import { beforeEach, describe, expect, it } from 'vitest'
2
+ import { SavingsLedger, savingsHash } from '../../src/runtime/savings.ts'
3
+
4
+ /** 模拟 pruner land 的真实调用序列:先压缩,后全文重读。 */
5
+ describe('savings ledger(诚实口径)', () => {
6
+ let ledger: SavingsLedger
7
+ beforeEach(() => {
8
+ ledger = new SavingsLedger()
9
+ })
10
+
11
+ it('compression saving lands: gross = tokensBefore − tokensAfter, zero-negative ignored', () => {
12
+ ledger.recordSaving({
13
+ sessionId: 's1',
14
+ component: 'fresh',
15
+ tokensBefore: 10_000,
16
+ tokensAfter: 2_000,
17
+ basis: 'exact-tokenizer',
18
+ sourceSeq: 12,
19
+ originalText: 'const a = 1\n'.repeat(500),
20
+ })
21
+ const snap = ledger.snapshot('s1')
22
+ expect(snap.gross.exact).toBe(8_000)
23
+ expect(snap.net.exact).toBe(8_000)
24
+ // 无节省(没压掉任何东西)不入账
25
+ ledger.recordSaving({ sessionId: 's1', component: 'fresh', tokensBefore: 100, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 13 })
26
+ expect(ledger.snapshot('s1').gross.exact).toBe(8_000)
27
+ })
28
+
29
+ it('**先骨架后全文 = 负节省**:全文重读抵消原声称,净额可为负', () => {
30
+ const original = 'export function readFile() {\n // ...long body...\n}\n'.repeat(200)
31
+ ledger.recordSaving({
32
+ sessionId: 's1',
33
+ component: 'fresh',
34
+ tokensBefore: 5_000,
35
+ tokensAfter: 800,
36
+ basis: 'exact-tokenizer',
37
+ sourceSeq: 7,
38
+ originalText: original,
39
+ })
40
+ // 全文重读(同一原文 → 哈希配对):按全文计量记抵消
41
+ ledger.noteFullText({
42
+ sessionId: 's1',
43
+ seq: 40,
44
+ text: original,
45
+ measure: () => ({ tokens: 5_000, basis: 'exact-tokenizer' }),
46
+ })
47
+ const snap = ledger.snapshot('s1')
48
+ expect(snap.gross.exact).toBe(4_200)
49
+ expect(snap.offsets.exact).toBe(5_000)
50
+ expect(snap.net.exact).toBe(-800) // **负节省**
51
+ expect(snap.recentOffsets).toHaveLength(1)
52
+ expect(snap.recentOffsets[0]?.note).toContain('#7')
53
+ })
54
+
55
+ it('同一 (session, seq) 的全文只探测一次;抵消每个哈希只消费一次', () => {
56
+ const text = 'payload-body\n'.repeat(100)
57
+ ledger.recordSaving({ sessionId: 's1', component: 'history', tokensBefore: 900, tokensAfter: 100, basis: 'characters', sourceSeq: 3, originalText: text })
58
+ const measure = () => ({ tokens: 900, basis: 'characters' as const })
59
+ ledger.noteFullText({ sessionId: 's1', seq: 30, text, measure })
60
+ ledger.noteFullText({ sessionId: 's1', seq: 30, text, measure }) // 同 seq 重放:忽略
61
+ expect(ledger.snapshot('s1').offsets.estimated).toBe(900)
62
+ ledger.noteFullText({ sessionId: 's1', seq: 31, text: text + '\n', measure }) // 新 seq、同哈希:已消费,不再抵消
63
+ expect(ledger.snapshot('s1').offsets.estimated).toBe(900)
64
+ })
65
+
66
+ it('跨会话不串账;retrieve 抵消走估算口径分列', () => {
67
+ const text = 'data\n'.repeat(50)
68
+ ledger.recordSaving({ sessionId: 's1', component: 'fresh', tokensBefore: 1_000, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 1, originalText: text })
69
+ ledger.noteFullText({ sessionId: 's2', seq: 1, text, measure: () => ({ tokens: 1_000, basis: 'exact-tokenizer' }) })
70
+ expect(ledger.snapshot('s1').offsets.exact).toBe(0)
71
+ ledger.recordOffset({ sessionId: 's1', component: 'retrieve', tokens: 300, basis: 'characters' })
72
+ const snap = ledger.snapshot()
73
+ expect(snap.net.exact).toBe(900)
74
+ expect(snap.net.estimated).toBe(-300) // 口径分列:估算抵消不污染精确净额
75
+ expect(snap.sessions).toBe(1)
76
+ })
77
+
78
+ it('savingsHash 规整行尾与首尾空白:同文件两次读取的 innocuous 差异仍配对', () => {
79
+ expect(savingsHash('a\nb\r\nc')).toBe(savingsHash('a\nb\nc'))
80
+ expect(savingsHash(' a\nb ')).toBe(savingsHash('a\nb'))
81
+ expect(savingsHash('a')).not.toBe(savingsHash('b'))
82
+ })
83
+ })
84
+
85
+ describe('savings ledger(usage 聚合与分桶,monitor 口径)', () => {
86
+ let ledger: SavingsLedger
87
+ beforeEach(() => {
88
+ ledger = new SavingsLedger()
89
+ })
90
+
91
+ it('aggregates official usage per session and computes cache hit rate', () => {
92
+ ledger.recordUsage('s1', { inputTokens: 100, outputTokens: 500, cacheReadTokens: 9_000, cacheWriteTokens: 400 })
93
+ ledger.recordUsage('s1', { inputTokens: 200, outputTokens: 300, cacheReadTokens: 8_000, cacheWriteTokens: 500 })
94
+ const snap = ledger.snapshot('s1')
95
+ expect(snap.usage.requests).toBe(2)
96
+ expect(snap.usage.inputTokens).toBe(300)
97
+ expect(snap.usage.cacheReadTokens).toBe(17_000)
98
+ expect(snap.usage.cacheHitRate).toBeCloseTo(17_000 / 18_200, 3)
99
+ })
100
+
101
+ it('buckets sessions by net savings; per-session list only in global snapshot', () => {
102
+ ledger.recordUsage('s1', { inputTokens: 10, outputTokens: 1, cacheReadTokens: 90, cacheWriteTokens: 0 })
103
+ ledger.recordUsage('s2', { inputTokens: 10, outputTokens: 1, cacheReadTokens: 10, cacheWriteTokens: 0 })
104
+ ledger.recordSaving({ sessionId: 's2', component: 'fresh', tokensBefore: 500, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 1 })
105
+ const global = ledger.snapshot()
106
+ expect(global.perSession).toHaveLength(2)
107
+ expect(global.perSession[0]!.sessionId).toBe('s2')
108
+ expect(global.perSession[0]!.cacheHitRate).toBe(0.5)
109
+ const single = ledger.snapshot('s1')
110
+ expect(single.perSession).toHaveLength(0)
111
+ })
112
+
113
+ it('sessionSummaryLine renders one-line account for dispose log', () => {
114
+ ledger.recordUsage('s1', { inputTokens: 100, outputTokens: 10, cacheReadTokens: 900, cacheWriteTokens: 0 })
115
+ ledger.recordSaving({ sessionId: 's1', component: 'fresh', tokensBefore: 400, tokensAfter: 100, basis: 'exact-tokenizer', sourceSeq: 2 })
116
+ const line = ledger.sessionSummaryLine('s1')
117
+ expect(line).toContain('net=300(exact)/0(est)')
118
+ expect(line).toContain('cacheHit=90%')
119
+ })
120
+ })