vomebook commited on
Commit ยท
476874a
1
Parent(s): f778ae5
Reduce PDF text search cooperative timer overhead
Browse files
static/reader/search/reader-book-text.js
CHANGED
|
@@ -34,6 +34,8 @@ function pattern(query) {
|
|
| 34 |
}
|
| 35 |
|
| 36 |
const CHECKPOINT_STRIDE = 256;
|
|
|
|
|
|
|
| 37 |
|
| 38 |
export function hitBoxes(page, start, length) {
|
| 39 |
const begin = codePointLength(page.text.slice(0, start));
|
|
@@ -60,7 +62,7 @@ function hitBoxesAtOffsets(page, begin, end) {
|
|
| 60 |
export async function searchBookText(book, query, options = {}) {
|
| 61 |
const { current = () => true, yieldTask = () => new Promise(r => setTimeout(r, 0)), progress = null } = options;
|
| 62 |
const counts = [], checkpoints = [], re = pattern(query);
|
| 63 |
-
let total = 0;
|
| 64 |
if (!query) return { total: 0, page: () => ({ total: 0, offset: 0, pageSize: 50, results: [] }) };
|
| 65 |
const pageCache = new Map();
|
| 66 |
const indexResult = { get total() { return total; }, page(offset = 0, pageSize = 50) {
|
|
@@ -128,14 +130,25 @@ export async function searchBookText(book, query, options = {}) {
|
|
| 128 |
count++;
|
| 129 |
if (count % 2048 === 0) {
|
| 130 |
await yieldTask();
|
|
|
|
|
|
|
| 131 |
if (!current()) throw new DOMException("Search cancelled", "AbortError");
|
| 132 |
}
|
| 133 |
}
|
|
|
|
| 134 |
counts.push(count);
|
| 135 |
total += count;
|
| 136 |
if (progress && (index === 0 || (count && total <= 50) || index % 16 === 15 || index === book.pages.length - 1))
|
| 137 |
await progress(indexResult, index + 1, book.pages.length);
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
}
|
| 140 |
return indexResult;
|
| 141 |
}
|
|
|
|
| 34 |
}
|
| 35 |
|
| 36 |
const CHECKPOINT_STRIDE = 256;
|
| 37 |
+
const SEARCH_YIELD_MS = 8;
|
| 38 |
+
const SEARCH_YIELD_UNITS = 256 * 1024;
|
| 39 |
|
| 40 |
export function hitBoxes(page, start, length) {
|
| 41 |
const begin = codePointLength(page.text.slice(0, start));
|
|
|
|
| 62 |
export async function searchBookText(book, query, options = {}) {
|
| 63 |
const { current = () => true, yieldTask = () => new Promise(r => setTimeout(r, 0)), progress = null } = options;
|
| 64 |
const counts = [], checkpoints = [], re = pattern(query);
|
| 65 |
+
let total = 0, deadline = performance.now() + SEARCH_YIELD_MS, pendingUnits = 0;
|
| 66 |
if (!query) return { total: 0, page: () => ({ total: 0, offset: 0, pageSize: 50, results: [] }) };
|
| 67 |
const pageCache = new Map();
|
| 68 |
const indexResult = { get total() { return total; }, page(offset = 0, pageSize = 50) {
|
|
|
|
| 130 |
count++;
|
| 131 |
if (count % 2048 === 0) {
|
| 132 |
await yieldTask();
|
| 133 |
+
deadline = performance.now() + SEARCH_YIELD_MS;
|
| 134 |
+
pendingUnits = 0;
|
| 135 |
if (!current()) throw new DOMException("Search cancelled", "AbortError");
|
| 136 |
}
|
| 137 |
}
|
| 138 |
+
pendingUnits += book.pages[index].text.length;
|
| 139 |
counts.push(count);
|
| 140 |
total += count;
|
| 141 |
if (progress && (index === 0 || (count && total <= 50) || index % 16 === 15 || index === book.pages.length - 1))
|
| 142 |
await progress(indexResult, index + 1, book.pages.length);
|
| 143 |
+
// Check at the existing 16-page boundaries. The time budget avoids
|
| 144 |
+
// gratuitous timer clamping on short pages; the volume guard still yields
|
| 145 |
+
// when a background tab's clock has coarse resolution or is paused.
|
| 146 |
+
if (index % 16 === 0 && (performance.now() >= deadline || pendingUnits >= SEARCH_YIELD_UNITS)) {
|
| 147 |
+
await yieldTask();
|
| 148 |
+
if (!current()) throw new DOMException("Search cancelled", "AbortError");
|
| 149 |
+
deadline = performance.now() + SEARCH_YIELD_MS;
|
| 150 |
+
pendingUnits = 0;
|
| 151 |
+
}
|
| 152 |
}
|
| 153 |
return indexResult;
|
| 154 |
}
|
tests/reader/pdf-search/test_pdf_book_worker_browser.py
CHANGED
|
@@ -574,6 +574,66 @@ class PdfBookWorkerBrowserTests(unittest.TestCase):
|
|
| 574 |
self.assertEqual(result['first'].get('error'),'AbortError')
|
| 575 |
self.assertEqual(result['retry']['value']['total'],180)
|
| 576 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
def test_search_preempts_inflight_prefetch(self):
|
| 578 |
self.state['block_path'] = f'{BASE}/book-text.json.gz'
|
| 579 |
config = {'url': self.resource(self.state['block_path']),
|
|
|
|
| 574 |
self.assertEqual(result['first'].get('error'),'AbortError')
|
| 575 |
self.assertEqual(result['retry']['value']['total'],180)
|
| 576 |
|
| 577 |
+
def test_large_legacy_worker_search_replacement_keeps_cancellation(self):
|
| 578 |
+
target = f'{BASE}/book-text.json.gz'
|
| 579 |
+
text = 'ๆฎ้ๆๆฌ๐' * 2000
|
| 580 |
+
packed_book = packed({'version':2, 'kind':'pdf-book-text', 'complete':True,
|
| 581 |
+
'offset_unit':'unicode-codepoint', 'source_sha256':SOURCE_SHA, 'page_count':100,
|
| 582 |
+
'pages':[{'page':number, 'text':text, 'layout':{'offset_unit':'unicode-codepoint'}, 'text_spans':[]}
|
| 583 |
+
for number in range(1,101)]})
|
| 584 |
+
with self.server.state_lock:
|
| 585 |
+
self.server.resources[target] = packed_book
|
| 586 |
+
config = {'url':self.resource(target),'bytes':len(packed_book),'sha256':digest(packed_book),
|
| 587 |
+
'pageCount':100,'sourceSha':SOURCE_SHA}
|
| 588 |
+
page = self.make_page()
|
| 589 |
+
result = page.evaluate('''async config=>{
|
| 590 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 591 |
+
const client=window.client=createPdfBookSearch(config);
|
| 592 |
+
await window.deadline(client.prefetch(),'legacy prefetch');
|
| 593 |
+
const old=window.capture(client.search('missing'),'superseded');
|
| 594 |
+
const replacement=window.capture(client.search('ๆฎ้'),'replacement');
|
| 595 |
+
const [first,second]=await Promise.all([old,replacement]);
|
| 596 |
+
const tail=await window.deadline(client.page(199950),'deep page');
|
| 597 |
+
return {first,second,tail};
|
| 598 |
+
}''', config)
|
| 599 |
+
self.assertEqual(result['first'].get('error'),'AbortError')
|
| 600 |
+
self.assertEqual(result['second']['value']['total'],200000)
|
| 601 |
+
self.assertEqual(result['tail']['offset'],199950)
|
| 602 |
+
self.assertEqual(len(result['tail']['results']),50)
|
| 603 |
+
self.assertEqual(result['tail']['results'][0]['page'],100)
|
| 604 |
+
self.assertEqual(result['tail']['results'][0]['start'],1950*len('ๆฎ้ๆๆฌ๐'.encode('utf-16-le'))//2)
|
| 605 |
+
|
| 606 |
+
def test_replacement_during_legacy_scan_keeps_progress_and_results(self):
|
| 607 |
+
target = f'{BASE}/book-text.json.gz'
|
| 608 |
+
text = 'ๆฎ้ๆๆฌ๐' * 2000
|
| 609 |
+
packed_book = packed({'version':2, 'kind':'pdf-book-text', 'complete':True,
|
| 610 |
+
'offset_unit':'unicode-codepoint', 'source_sha256':SOURCE_SHA, 'page_count':100,
|
| 611 |
+
'pages':[{'page':number, 'text':text, 'layout':{'offset_unit':'unicode-codepoint'}, 'text_spans':[]}
|
| 612 |
+
for number in range(1,101)]})
|
| 613 |
+
with self.server.state_lock:
|
| 614 |
+
self.server.resources[target] = packed_book
|
| 615 |
+
config = {'url':self.resource(target),'bytes':len(packed_book),'sha256':digest(packed_book),
|
| 616 |
+
'pageCount':100,'sourceSha':SOURCE_SHA}
|
| 617 |
+
page = self.make_page()
|
| 618 |
+
result = page.evaluate('''async config=>{
|
| 619 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 620 |
+
const client=window.client=createPdfBookSearch(config);
|
| 621 |
+
await window.deadline(client.prefetch(),'legacy prefetch');
|
| 622 |
+
let replacement, observed=0;
|
| 623 |
+
const old=window.capture(client.search('missing',progress=>{
|
| 624 |
+
observed++;
|
| 625 |
+
if (!replacement) replacement=window.capture(client.search('ๆฎ้'),'replacement after progress');
|
| 626 |
+
}),'superseded after progress');
|
| 627 |
+
const first=await old;
|
| 628 |
+
if (!replacement) return {first,observed};
|
| 629 |
+
const second=await replacement;
|
| 630 |
+
return {first,second,observed};
|
| 631 |
+
}''',config)
|
| 632 |
+
self.assertGreaterEqual(result['observed'],1,'replacement must begin after actual Worker progress')
|
| 633 |
+
self.assertEqual(result['first'].get('error'),'AbortError')
|
| 634 |
+
self.assertEqual(result['second']['value']['total'],200000)
|
| 635 |
+
self.assertEqual(len(result['second']['value']['results']),50)
|
| 636 |
+
|
| 637 |
def test_search_preempts_inflight_prefetch(self):
|
| 638 |
self.state['block_path'] = f'{BASE}/book-text.json.gz'
|
| 639 |
config = {'url': self.resource(self.state['block_path']),
|
tests/reader/pdf-search/test_reader_book_text.mjs
CHANGED
|
@@ -118,4 +118,37 @@ try {
|
|
| 118 |
assert.equal(iteratedUnits,0,"box-free pages must not count prefix code points");
|
| 119 |
} finally { String.prototype[Symbol.iterator] = originalIterator; }
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
console.log("reader book text search contracts passed");
|
|
|
|
| 118 |
assert.equal(iteratedUnits,0,"box-free pages must not count prefix code points");
|
| 119 |
} finally { String.prototype[Symbol.iterator] = originalIterator; }
|
| 120 |
|
| 121 |
+
// Page scanning cooperates with Worker cancellation without a timer per tiny
|
| 122 |
+
// set of pages. A deterministic fake clock proves the deadline and byte guard.
|
| 123 |
+
const schedulerClock=globalThis.performance;
|
| 124 |
+
try {
|
| 125 |
+
Object.defineProperty(globalThis,'performance',{configurable:true,value:{now:()=>0}});
|
| 126 |
+
let yields=0;
|
| 127 |
+
const short={pages:Array.from({length:160},(_,index)=>({page:index+1,text:'x needle'}))};
|
| 128 |
+
let fast=await searchBookText(short,'needle',{yieldTask:async()=>{yields++;}});
|
| 129 |
+
assert.equal(fast.total,160);assert.equal(yields,0,'tiny pages should not schedule unnecessary timers');
|
| 130 |
+
const bulky={pages:Array.from({length:40},(_,index)=>({page:index+1,text:'x'.repeat(20000)}))};
|
| 131 |
+
yields=0;fast=await searchBookText(bulky,'absent',{yieldTask:async()=>{yields++;}});
|
| 132 |
+
assert.equal(fast.total,0);assert.ok(yields>0,'byte budget must yield even when the clock does not advance');
|
| 133 |
+
let live=true,firstYield;
|
| 134 |
+
const blocked=new Promise(resolve=>{firstYield=resolve;});
|
| 135 |
+
const cancelled=searchBookText(bulky,'absent',{current:()=>live,yieldTask:async()=>{
|
| 136 |
+
firstYield();await new Promise(resolve=>{globalThis.__releaseBookTextYield=resolve;});}});
|
| 137 |
+
await blocked;live=false;globalThis.__releaseBookTextYield();delete globalThis.__releaseBookTextYield;
|
| 138 |
+
await assert.rejects(cancelled,error=>error.name==='AbortError');
|
| 139 |
+
let finalLive=true,releaseFinal,startedFinal;
|
| 140 |
+
const finalWaiting=new Promise(resolve=>{startedFinal=resolve;});
|
| 141 |
+
const final=searchBookText({pages:[{page:1,text:'x'.repeat(300000)}]},'missing',{
|
| 142 |
+
current:()=>finalLive,yieldTask:()=>new Promise(resolve=>{releaseFinal=resolve;startedFinal();})});
|
| 143 |
+
await finalWaiting;finalLive=false;releaseFinal();
|
| 144 |
+
await assert.rejects(final,error=>error.name==='AbortError','cancellation at the final yield must not resolve a stale index');
|
| 145 |
+
yields=0;
|
| 146 |
+
const dense={pages:[{page:1,text:'x'.repeat(4096)}]};
|
| 147 |
+
const denseResult=await searchBookText(dense,'x',{yieldTask:async()=>{yields++;}});
|
| 148 |
+
assert.equal(denseResult.total,4096);assert.equal(yields,2,'dense-match cancellation checkpoints remain unchanged');
|
| 149 |
+
let clock=0;Object.defineProperty(globalThis,'performance',{configurable:true,value:{now:()=>clock+=9}});
|
| 150 |
+
yields=0;await searchBookText(short,'needle',{yieldTask:async()=>{yields++;}});
|
| 151 |
+
assert.ok(yields>0,'elapsed-time budget must retain cooperative yields');
|
| 152 |
+
} finally {Object.defineProperty(globalThis,'performance',{configurable:true,value:schedulerClock});}
|
| 153 |
+
|
| 154 |
console.log("reader book text search contracts passed");
|