vomebook commited on
Commit ·
da0761c
1
Parent(s): f3e7bb2
Reuse verified PDF partition during result paging
Browse files
static/reader/search/workers/reader-pdf-book-search-worker.mjs
CHANGED
|
@@ -8,6 +8,8 @@ const pause = () => new Promise(resolve => setTimeout(resolve, 0));
|
|
| 8 |
// Hold at most one small compressed future partition. Decompression and
|
| 9 |
// verification happen only when that partition reaches the head of the scan.
|
| 10 |
const PARTITION_LOOKAHEAD_MAX_BYTES = 1024 * 1024;
|
|
|
|
|
|
|
| 11 |
let configuration, book, pendingBook, controller, active = 0, session;
|
| 12 |
const partitionRequests = new Set();
|
| 13 |
const idlePartitionWaiters = new Set();
|
|
@@ -196,7 +198,23 @@ async function loadSearchPartition(part, current, owners = null, prefetched = nu
|
|
| 196 |
async function searchPartitions(query, current, progress) {
|
| 197 |
validateSearchConfiguration();
|
| 198 |
const counts = [], first = [];
|
| 199 |
-
let total = 0, complete = false;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
const decorate = (results, pages) => results.map(hit => ({...hit,
|
| 201 |
textGeneration: pages[hit.page - pages[0].page].text_generation}));
|
| 202 |
const index = {async page(requested = 0) {
|
|
@@ -207,9 +225,17 @@ async function searchPartitions(query, current, progress) {
|
|
| 207 |
for (let i = 0; i < counts.length && results.length < 50; i++) {
|
| 208 |
if (!current()) throw aborted();
|
| 209 |
if (skipped + counts[i] <= offset) {skipped += counts[i]; continue;}
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
let position = Math.max(0, offset - skipped);
|
| 214 |
while (position < local.total && results.length < 50) {
|
| 215 |
const page = local.page(position);
|
|
|
|
| 8 |
// Hold at most one small compressed future partition. Decompression and
|
| 9 |
// verification happen only when that partition reaches the head of the scan.
|
| 10 |
const PARTITION_LOOKAHEAD_MAX_BYTES = 1024 * 1024;
|
| 11 |
+
// Keep at most one small, already validated partition search index per query.
|
| 12 |
+
const PARTITION_PAGE_CACHE_BYTES = 1024 * 1024;
|
| 13 |
let configuration, book, pendingBook, controller, active = 0, session;
|
| 14 |
const partitionRequests = new Set();
|
| 15 |
const idlePartitionWaiters = new Set();
|
|
|
|
| 198 |
async function searchPartitions(query, current, progress) {
|
| 199 |
validateSearchConfiguration();
|
| 200 |
const counts = [], first = [];
|
| 201 |
+
let total = 0, complete = false, retained = null;
|
| 202 |
+
const remember = (number, part, local) => {
|
| 203 |
+
retained = null;
|
| 204 |
+
let bytes = 0;
|
| 205 |
+
// Validate allocation cost before walking the complete text. JSON escaping
|
| 206 |
+
// can expand it, so count the actual UTF-8 representation as well.
|
| 207 |
+
for (const page of part.pages) {
|
| 208 |
+
bytes += page.text.length * 2;
|
| 209 |
+
if (bytes > PARTITION_PAGE_CACHE_BYTES) return;
|
| 210 |
+
}
|
| 211 |
+
try {
|
| 212 |
+
if (new TextEncoder().encode(JSON.stringify(part)).byteLength > PARTITION_PAGE_CACHE_BYTES) return;
|
| 213 |
+
} catch (_) { return; } // Allocation failure must not break an otherwise valid result page.
|
| 214 |
+
// The index owns this SHA-256-verified immutable snapshot and checkpoints.
|
| 215 |
+
// Reuse is scoped to this query; no unverified or oversized body is kept.
|
| 216 |
+
retained = {number, part, local};
|
| 217 |
+
};
|
| 218 |
const decorate = (results, pages) => results.map(hit => ({...hit,
|
| 219 |
textGeneration: pages[hit.page - pages[0].page].text_generation}));
|
| 220 |
const index = {async page(requested = 0) {
|
|
|
|
| 225 |
for (let i = 0; i < counts.length && results.length < 50; i++) {
|
| 226 |
if (!current()) throw aborted();
|
| 227 |
if (skipped + counts[i] <= offset) {skipped += counts[i]; continue;}
|
| 228 |
+
let part, local;
|
| 229 |
+
if (retained?.number === i) ({part, local} = retained);
|
| 230 |
+
else {
|
| 231 |
+
retained = null;
|
| 232 |
+
part = await loadSearchPartition(configuration.partitions[i], current);
|
| 233 |
+
local = await searchBookText(part, query, {current, yieldTask: pause});
|
| 234 |
+
if (!current()) throw aborted();
|
| 235 |
+
if (local.total !== counts[i]) throw new Error("PDF_V3_GENERATION_CHANGED");
|
| 236 |
+
remember(i, part, local);
|
| 237 |
+
}
|
| 238 |
+
if (!current()) throw aborted();
|
| 239 |
let position = Math.max(0, offset - skipped);
|
| 240 |
while (position < local.total && results.length < 50) {
|
| 241 |
const page = local.page(position);
|
tests/reader/pdf-search/test_pdf_book_worker_browser.py
CHANGED
|
@@ -62,7 +62,7 @@ class Handler(SimpleHTTPRequestHandler):
|
|
| 62 |
parts = path.split('/')
|
| 63 |
if len(parts) > 3:
|
| 64 |
parts[3] = 'bbbbbbbbbbbbbbbb'
|
| 65 |
-
body =
|
| 66 |
if body is None:
|
| 67 |
self.send_error(404)
|
| 68 |
return
|
|
@@ -112,6 +112,7 @@ class PdfBookWorkerBrowserTests(unittest.TestCase):
|
|
| 112 |
def setUpClass(cls):
|
| 113 |
cls.server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Handler, directory=str(ROOT)))
|
| 114 |
cls.server.state_lock = threading.Lock()
|
|
|
|
| 115 |
cls.server.state = None
|
| 116 |
cls.server.block_timed_out = threading.Event()
|
| 117 |
cls.server_thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
|
@@ -136,6 +137,7 @@ class PdfBookWorkerBrowserTests(unittest.TestCase):
|
|
| 136 |
with self.server.state_lock:
|
| 137 |
self.assertIsNone(self.server.state)
|
| 138 |
self.server.block_timed_out.clear()
|
|
|
|
| 139 |
self.server.state = self.state
|
| 140 |
self.addCleanup(self.cleanup_requests)
|
| 141 |
|
|
@@ -297,6 +299,125 @@ class PdfBookWorkerBrowserTests(unittest.TestCase):
|
|
| 297 |
self.assertTrue(all(hit['textGeneration'] == TEXT_GENERATION for hit in result['page']['results']))
|
| 298 |
self.assertEqual(self.state['peak'],2,'exactly one lookahead may overlap the first partition')
|
| 299 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
def test_partition_failure_never_commits_unverified_results(self):
|
| 301 |
page=self.make_page()
|
| 302 |
configuration=self.configuration()
|
|
|
|
| 62 |
parts = path.split('/')
|
| 63 |
if len(parts) > 3:
|
| 64 |
parts[3] = 'bbbbbbbbbbbbbbbb'
|
| 65 |
+
body = self.server.resources.get('/'.join(parts))
|
| 66 |
if body is None:
|
| 67 |
self.send_error(404)
|
| 68 |
return
|
|
|
|
| 112 |
def setUpClass(cls):
|
| 113 |
cls.server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Handler, directory=str(ROOT)))
|
| 114 |
cls.server.state_lock = threading.Lock()
|
| 115 |
+
cls.server.resources = dict(RESOURCES)
|
| 116 |
cls.server.state = None
|
| 117 |
cls.server.block_timed_out = threading.Event()
|
| 118 |
cls.server_thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
|
|
|
| 137 |
with self.server.state_lock:
|
| 138 |
self.assertIsNone(self.server.state)
|
| 139 |
self.server.block_timed_out.clear()
|
| 140 |
+
self.server.resources = dict(RESOURCES)
|
| 141 |
self.server.state = self.state
|
| 142 |
self.addCleanup(self.cleanup_requests)
|
| 143 |
|
|
|
|
| 299 |
self.assertTrue(all(hit['textGeneration'] == TEXT_GENERATION for hit in result['page']['results']))
|
| 300 |
self.assertEqual(self.state['peak'],2,'exactly one lookahead may overlap the first partition')
|
| 301 |
|
| 302 |
+
def test_result_page_cache_reuses_verified_index_and_resets_with_query(self):
|
| 303 |
+
page = self.make_page()
|
| 304 |
+
page.evaluate('''async config => {
|
| 305 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 306 |
+
window.client=createPdfBookSearch(config);
|
| 307 |
+
window.first=await window.deadline(client.search('needle'), 'initial search');
|
| 308 |
+
}''', self.configuration())
|
| 309 |
+
initial = list(self.state['paths'])
|
| 310 |
+
a = page.evaluate('''async() => {
|
| 311 |
+
const a=await window.deadline(client.page(50),'first page');
|
| 312 |
+
const b=await window.deadline(client.page(100),'cross-partition page');
|
| 313 |
+
const c=await window.deadline(client.page(150),'next partition reuse');
|
| 314 |
+
return {a,b,c};
|
| 315 |
+
}''')
|
| 316 |
+
self.assertEqual([a[k]['offset'] for k in ('a','b','c')], [50,100,150])
|
| 317 |
+
self.assertEqual([hit['page'] for hit in a['b']['results']], [1]*20+[2]*30)
|
| 318 |
+
self.assertTrue(all(hit['textGeneration'] == TEXT_GENERATION for k in a for hit in a[k]['results']))
|
| 319 |
+
first_path = f'{BASE}/search-000001-000001.json.gz'
|
| 320 |
+
second_path = f'{BASE}/search-000002-000002.json.gz'
|
| 321 |
+
self.assertEqual(self.state['paths'][len(initial):], [first_path,second_path])
|
| 322 |
+
page.evaluate('''async() => {window.same=await window.deadline(client.search('needle'),'new query');}''')
|
| 323 |
+
self.assertNotEqual(page.evaluate('window.first.session'),page.evaluate('window.same.session'))
|
| 324 |
+
self.assertEqual(self.state['paths'][len(initial):], [first_path,second_path,first_path,second_path])
|
| 325 |
+
page.evaluate('''async() => {window.second=await window.deadline(client.page(150),'new session page');}''')
|
| 326 |
+
self.assertEqual(self.state['paths'][-1], second_path)
|
| 327 |
+
self.assertEqual(len(self.state['paths']),len(initial)+5)
|
| 328 |
+
self.assertEqual(len(page.evaluate('window.second.results')),30)
|
| 329 |
+
|
| 330 |
+
def test_result_page_cache_never_masks_a_changed_uncached_partition(self):
|
| 331 |
+
page = self.make_page()
|
| 332 |
+
page.evaluate('''async config => {
|
| 333 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 334 |
+
window.client=createPdfBookSearch(config);
|
| 335 |
+
await window.deadline(client.search('needle'),'search');
|
| 336 |
+
await window.deadline(client.page(50),'retain first partition');
|
| 337 |
+
}''', self.configuration())
|
| 338 |
+
target = f'{BASE}/search-000002-000002.json.gz'
|
| 339 |
+
with self.server.state_lock:
|
| 340 |
+
self.server.resources[target] = PARTITION2[:-1] + bytes([PARTITION2[-1] ^ 1])
|
| 341 |
+
result = page.evaluate('''async()=>{
|
| 342 |
+
const failed=await window.capture(client.page(100),'changed partition');
|
| 343 |
+
const retry=await window.capture(client.page(50),'previous partition retry');
|
| 344 |
+
return {failed,retry};
|
| 345 |
+
}''')
|
| 346 |
+
self.assertIn('PDF_OCR_HASH_MISMATCH',result['failed'].get('message',''))
|
| 347 |
+
self.assertEqual(result['retry']['value']['offset'],50)
|
| 348 |
+
self.assertEqual(len(result['retry']['value']['results']),50)
|
| 349 |
+
self.assertEqual(self.state['paths'].count(f'{BASE}/search-000001-000001.json.gz'),3)
|
| 350 |
+
|
| 351 |
+
def test_result_cache_is_discarded_after_cancellation(self):
|
| 352 |
+
page = self.make_page()
|
| 353 |
+
page.evaluate('''async config => {
|
| 354 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 355 |
+
window.client=createPdfBookSearch(config);
|
| 356 |
+
await window.deadline(client.search('needle'),'search');
|
| 357 |
+
await window.deadline(client.page(50),'retain');
|
| 358 |
+
client.cancel();
|
| 359 |
+
}''', self.configuration())
|
| 360 |
+
target = f'{BASE}/search-000001-000001.json.gz'
|
| 361 |
+
self.assertEqual(self.state['paths'].count(target),2)
|
| 362 |
+
with self.server.state_lock:
|
| 363 |
+
self.server.resources[target] = PARTITION[:-1] + bytes([PARTITION[-1] ^ 1])
|
| 364 |
+
invalid = page.evaluate('''async()=>window.capture(client.page(50),'old session')''')
|
| 365 |
+
self.assertIn('取消或加载超时',invalid.get('message',''))
|
| 366 |
+
self.assertEqual(self.state['paths'].count(target),2)
|
| 367 |
+
result = page.evaluate('''async()=>window.capture(client.search('needle'),'search after cancel')''')
|
| 368 |
+
self.assertIn('PDF_OCR_HASH_MISMATCH',result.get('message',''))
|
| 369 |
+
self.assertEqual(self.state['paths'].count(target),3)
|
| 370 |
+
|
| 371 |
+
def test_result_page_cache_bounds_json_expansion(self):
|
| 372 |
+
large = packed({
|
| 373 |
+
'version':1, 'kind':'pdf-search-text-partition', 'source_sha256':SOURCE_SHA,
|
| 374 |
+
'generation':GENERATION, 'offset_unit':'unicode-codepoint', 'start':1, 'end':1,
|
| 375 |
+
# UTF-16 text fits, but serializing these control characters needs
|
| 376 |
+
# six UTF-8 bytes apiece; it must not become a retained index.
|
| 377 |
+
'pages':[{'page':1, 'text':'needle '*120 + '\u0001'*180000,
|
| 378 |
+
'text_generation':TEXT_GENERATION}],
|
| 379 |
+
})
|
| 380 |
+
target = f'{BASE}/search-000001-000001.json.gz'
|
| 381 |
+
with self.server.state_lock:
|
| 382 |
+
self.server.resources[target] = large
|
| 383 |
+
config = self.configuration()
|
| 384 |
+
config['partitions'][0]['bytes'] = len(large)
|
| 385 |
+
config['partitions'][0]['sha256'] = digest(large)
|
| 386 |
+
page = self.make_page()
|
| 387 |
+
page.evaluate('''async config => {
|
| 388 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 389 |
+
window.client=createPdfBookSearch(config);
|
| 390 |
+
await window.deadline(client.search('needle'),'search');
|
| 391 |
+
await window.deadline(client.page(50),'first page');
|
| 392 |
+
await window.deadline(client.page(50),'repeated page');
|
| 393 |
+
}''', config)
|
| 394 |
+
self.assertEqual(self.state['paths'].count(target),3)
|
| 395 |
+
|
| 396 |
+
def test_result_page_cache_rejects_oversized_text(self):
|
| 397 |
+
large = packed({
|
| 398 |
+
'version':1, 'kind':'pdf-search-text-partition', 'source_sha256':SOURCE_SHA,
|
| 399 |
+
'generation':GENERATION, 'offset_unit':'unicode-codepoint', 'start':1, 'end':1,
|
| 400 |
+
'pages':[{'page':1, 'text':'needle '*120 + '中'*(1024*1024//2),
|
| 401 |
+
'text_generation':TEXT_GENERATION}],
|
| 402 |
+
})
|
| 403 |
+
target = f'{BASE}/search-000001-000001.json.gz'
|
| 404 |
+
with self.server.state_lock:
|
| 405 |
+
self.server.resources[target] = large
|
| 406 |
+
config = self.configuration()
|
| 407 |
+
config['partitions'][0]['bytes'] = len(large)
|
| 408 |
+
config['partitions'][0]['sha256'] = digest(large)
|
| 409 |
+
page = self.make_page()
|
| 410 |
+
result = page.evaluate('''async config => {
|
| 411 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 412 |
+
window.client=createPdfBookSearch(config);
|
| 413 |
+
await window.deadline(client.search('needle'),'search');
|
| 414 |
+
const a=await window.deadline(client.page(50),'first page');
|
| 415 |
+
const b=await window.deadline(client.page(50),'repeated page');
|
| 416 |
+
return {a,b};
|
| 417 |
+
}''',config)
|
| 418 |
+
self.assertEqual(result['a']['results'],result['b']['results'])
|
| 419 |
+
self.assertEqual(self.state['paths'].count(target),3)
|
| 420 |
+
|
| 421 |
def test_partition_failure_never_commits_unverified_results(self):
|
| 422 |
page=self.make_page()
|
| 423 |
configuration=self.configuration()
|