Files
PiAgentUI/extensions/piagentui-stat-cache.test.ts
evandro e8927ebf78 perf(extension): cache parsed session files by mtime and size
GET /api/sessions (and every session lookup) re-read and JSON.parsed every
.jsonl session file synchronously on each request, blocking the agent's
event loop. Parsed metadata is now cached per path (bounded to 500 entries)
and invalidated when mtime or size changes.
2026-10-10 04:23:16 -03:00

51 lines
1.8 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { createStatCache } from './piagentui-stat-cache.js'
const stamp = (mtimeMs: number, size = 10) => ({ mtimeMs, size })
describe('createStatCache', () => {
it('misses for unknown paths and hits for the same stamp', () => {
const cache = createStatCache<string>()
expect(cache.get('a', stamp(1))).toBeUndefined()
cache.set('a', stamp(1), 'x')
expect(cache.get('a', stamp(1))).toEqual({ value: 'x' })
})
it('treats a changed mtime or size as a miss and drops the stale entry', () => {
const cache = createStatCache<string>()
cache.set('a', stamp(1, 10), 'x')
expect(cache.get('a', stamp(2, 10))).toBeUndefined()
expect(cache.size).toBe(0)
cache.set('a', stamp(1, 10), 'x')
expect(cache.get('a', stamp(1, 11))).toBeUndefined()
})
it('can cache null values', () => {
const cache = createStatCache<string | null>()
cache.set('a', stamp(1), null)
expect(cache.get('a', stamp(1))).toEqual({ value: null })
})
it('evicts the oldest entries beyond the limit', () => {
const cache = createStatCache<number>(2)
cache.set('a', stamp(1), 1)
cache.set('b', stamp(1), 2)
cache.set('c', stamp(1), 3)
expect(cache.size).toBe(2)
expect(cache.get('a', stamp(1))).toBeUndefined()
expect(cache.get('b', stamp(1))).toEqual({ value: 2 })
expect(cache.get('c', stamp(1))).toEqual({ value: 3 })
})
it('refreshing a key moves it to the newest position', () => {
const cache = createStatCache<number>(2)
cache.set('a', stamp(1), 1)
cache.set('b', stamp(1), 2)
cache.set('a', stamp(2), 11)
cache.set('c', stamp(1), 3)
expect(cache.get('b', stamp(1))).toBeUndefined()
expect(cache.get('a', stamp(2))).toEqual({ value: 11 })
})
})