Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions apps/sim/lib/sim-search/live/read-window.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* @vitest-environment node
*/
import { describe, expect, it } from 'vitest'
import { encodedWindowEnd } from '@/lib/sim-search/live/read-window'

const encoded = (text: string) => JSON.stringify(text).length - 2

describe('encodedWindowEnd', () => {
it('returns the longest window it found to fit when escapes lead the text', () => {
const content = `${'"'.repeat(1_000)}${'x'.repeat(20_000)}`
const end = encodedWindowEnd(content, 0, 20_000, 8_000)
expect(end).toBe(19_000)
expect(encoded(content.slice(0, end))).toBeLessThanOrEqual(20_000)
})
})
6 changes: 5 additions & 1 deletion apps/sim/lib/sim-search/live/read-window.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/** Characters one standard read returns, the page budget indexed document reads use. */
export const READ_WINDOW_CHARACTERS = 8000

/** Times a window is shortened to fit its budget before the minimum is used instead. */
const MAX_SHRINKS = 3

/**
* Where a window of `content` from `start` ends so its text, as JSON encodes it, fits `budget`
* characters. JSON escapes quotes, backslashes and line breaks, so a window is shortened until its
Expand All @@ -13,9 +16,10 @@ export function encodedWindowEnd(
minimumEnd: number
): number {
let end = Math.min(content.length, start + budget)
for (let attempt = 0; attempt < 3 && end > minimumEnd; attempt++) {
for (let shrinks = 0; end > minimumEnd; shrinks++) {
const encoded = JSON.stringify(content.slice(start, end)).length - 2
if (encoded <= budget) return end
if (shrinks === MAX_SHRINKS) break
end = start + Math.floor(((end - start) * budget) / encoded)
}
return minimumEnd
Expand Down
Loading