vomebook commited on
Commit ·
ecb0cd4
1
Parent(s): ec68d6c
Overlap bounded PDF text partition fetches
Browse files
static/reader/search/workers/reader-pdf-book-search-worker.mjs
CHANGED
|
@@ -5,8 +5,26 @@ import { validPdfBookUrl, searchPath } from "../reader-pdf-book-url.mjs";
|
|
| 5 |
const aborted = () => new DOMException("Search cancelled", "AbortError");
|
| 6 |
const limit = self.VoiceOfMLReaderSecurity.LIMITS.chapterTotalBytes;
|
| 7 |
const pause = () => new Promise(resolve => setTimeout(resolve, 0));
|
|
|
|
|
|
|
|
|
|
| 8 |
let configuration, book, pendingBook, controller, active = 0, session;
|
| 9 |
const partitionRequests = new Set();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
/** @overload
|
| 12 |
* @param {ReadableStream<Uint8Array>} stream
|
|
@@ -126,23 +144,43 @@ function validateSearchConfiguration() {
|
|
| 126 |
if (next !== configuration.pageCount + 1) throw new Error("PDF_TEXT_INDEX_INCOMPLETE");
|
| 127 |
}
|
| 128 |
|
| 129 |
-
async function
|
| 130 |
if (!current()) throw aborted();
|
| 131 |
const request = new AbortController();
|
| 132 |
partitionRequests.add(request);
|
|
|
|
| 133 |
const timer = setTimeout(() => request.abort(), 120000);
|
| 134 |
try {
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
const digest = [...new Uint8Array(await crypto.subtle.digest("SHA-256", packed))]
|
| 139 |
.map(value => value.toString(16).padStart(2, "0")).join("");
|
| 140 |
if (digest !== part.sha256) throw new Error("PDF_OCR_HASH_MISMATCH");
|
| 141 |
const stream = new ReadableStream({start(owner) {owner.enqueue(packed); owner.close();}});
|
| 142 |
packed = null;
|
| 143 |
const value = JSON.parse(await readBounded(
|
| 144 |
-
stream.pipeThrough(new DecompressionStream("gzip")),
|
| 145 |
-
if (!current() ||
|
| 146 |
if (value.version !== 1 || value.kind !== "pdf-search-text-partition" ||
|
| 147 |
value.source_sha256 !== configuration.sourceSha || value.generation !== configuration.generation ||
|
| 148 |
value.offset_unit !== "unicode-codepoint" || value.start !== part.start || value.end !== part.end ||
|
|
@@ -152,11 +190,7 @@ async function loadSearchPartition(part, current) {
|
|
| 152 |
Object.keys(page).some(key => !["page", "text", "text_generation"].includes(key))))
|
| 153 |
throw new Error("PDF_TEXT_INDEX_INVALID");
|
| 154 |
return value;
|
| 155 |
-
}
|
| 156 |
-
clearTimeout(timer);
|
| 157 |
-
partitionRequests.delete(request);
|
| 158 |
-
request.abort();
|
| 159 |
-
}
|
| 160 |
}
|
| 161 |
|
| 162 |
async function searchPartitions(query, current, progress) {
|
|
@@ -187,20 +221,48 @@ async function searchPartitions(query, current, progress) {
|
|
| 187 |
}
|
| 188 |
return {total, offset, pageSize: 50, results, complete};
|
| 189 |
}};
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
}
|
| 202 |
-
complete = true;
|
| 203 |
-
return index;
|
| 204 |
}
|
| 205 |
|
| 206 |
self.onmessage = async ({ data }) => {
|
|
@@ -209,7 +271,7 @@ self.onmessage = async ({ data }) => {
|
|
| 209 |
active++;
|
| 210 |
session = null;
|
| 211 |
controller?.abort();
|
| 212 |
-
|
| 213 |
return;
|
| 214 |
}
|
| 215 |
if (data.type !== "search" && data.type !== "page" && data.type !== "prefetch") return;
|
|
@@ -217,8 +279,12 @@ self.onmessage = async ({ data }) => {
|
|
| 217 |
const current = () => token === active;
|
| 218 |
try {
|
| 219 |
if (data.type === "search") {
|
| 220 |
-
|
| 221 |
session = null;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
const query = String(data.query || "").trim();
|
| 223 |
if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符");
|
| 224 |
if (controller?.signal.aborted && pendingBook) await pendingBook.catch(() => {});
|
|
|
|
| 5 |
const aborted = () => new DOMException("Search cancelled", "AbortError");
|
| 6 |
const limit = self.VoiceOfMLReaderSecurity.LIMITS.chapterTotalBytes;
|
| 7 |
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();
|
| 14 |
+
|
| 15 |
+
function abortPartitionRequests() {
|
| 16 |
+
for (const request of partitionRequests) request.abort();
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
function waitForPartitionRequests() {
|
| 20 |
+
if (!partitionRequests.size) return Promise.resolve();
|
| 21 |
+
return new Promise(resolve => idlePartitionWaiters.add(resolve));
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
function canPrefetchPartition(connection, bytes) {
|
| 25 |
+
return !connection?.saveData && !["slow-2g", "2g"].includes(connection?.effectiveType) &&
|
| 26 |
+
Number.isSafeInteger(bytes) && bytes > 0 && bytes <= PARTITION_LOOKAHEAD_MAX_BYTES;
|
| 27 |
+
}
|
| 28 |
|
| 29 |
/** @overload
|
| 30 |
* @param {ReadableStream<Uint8Array>} stream
|
|
|
|
| 144 |
if (next !== configuration.pageCount + 1) throw new Error("PDF_TEXT_INDEX_INCOMPLETE");
|
| 145 |
}
|
| 146 |
|
| 147 |
+
async function withPartitionRequest(current, owners, action) {
|
| 148 |
if (!current()) throw aborted();
|
| 149 |
const request = new AbortController();
|
| 150 |
partitionRequests.add(request);
|
| 151 |
+
owners?.add(request);
|
| 152 |
const timer = setTimeout(() => request.abort(), 120000);
|
| 153 |
try {
|
| 154 |
+
return await action(request.signal);
|
| 155 |
+
} finally {
|
| 156 |
+
clearTimeout(timer);
|
| 157 |
+
partitionRequests.delete(request);
|
| 158 |
+
owners?.delete(request);
|
| 159 |
+
request.abort();
|
| 160 |
+
if (!partitionRequests.size) {
|
| 161 |
+
for (const resolve of idlePartitionWaiters) resolve();
|
| 162 |
+
idlePartitionWaiters.clear();
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
async function fetchPartitionBytes(part, signal) {
|
| 168 |
+
const response = await fetch(part.url, {signal, credentials: "omit"});
|
| 169 |
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
| 170 |
+
return readBounded(response.body, signal, part.bytes);
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
async function loadSearchPartition(part, current, owners = null, prefetched = null) {
|
| 174 |
+
return withPartitionRequest(current, owners, async signal => {
|
| 175 |
+
let packed = prefetched || await fetchPartitionBytes(part, signal);
|
| 176 |
const digest = [...new Uint8Array(await crypto.subtle.digest("SHA-256", packed))]
|
| 177 |
.map(value => value.toString(16).padStart(2, "0")).join("");
|
| 178 |
if (digest !== part.sha256) throw new Error("PDF_OCR_HASH_MISMATCH");
|
| 179 |
const stream = new ReadableStream({start(owner) {owner.enqueue(packed); owner.close();}});
|
| 180 |
packed = null;
|
| 181 |
const value = JSON.parse(await readBounded(
|
| 182 |
+
stream.pipeThrough(new DecompressionStream("gzip")), signal, null, true));
|
| 183 |
+
if (!current() || signal.aborted) throw aborted();
|
| 184 |
if (value.version !== 1 || value.kind !== "pdf-search-text-partition" ||
|
| 185 |
value.source_sha256 !== configuration.sourceSha || value.generation !== configuration.generation ||
|
| 186 |
value.offset_unit !== "unicode-codepoint" || value.start !== part.start || value.end !== part.end ||
|
|
|
|
| 190 |
Object.keys(page).some(key => !["page", "text", "text_generation"].includes(key))))
|
| 191 |
throw new Error("PDF_TEXT_INDEX_INVALID");
|
| 192 |
return value;
|
| 193 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
}
|
| 195 |
|
| 196 |
async function searchPartitions(query, current, progress) {
|
|
|
|
| 221 |
}
|
| 222 |
return {total, offset, pageSize: 50, results, complete};
|
| 223 |
}};
|
| 224 |
+
const owners = new Set(), connection = self.navigator?.connection;
|
| 225 |
+
let pending = null;
|
| 226 |
+
try {
|
| 227 |
+
for (let position = 0; position < configuration.partitions.length; position++) {
|
| 228 |
+
if (!current()) throw aborted();
|
| 229 |
+
const part = configuration.partitions[position], ahead = pending;
|
| 230 |
+
pending = null;
|
| 231 |
+
const valuePromise = ahead ? ahead.then(outcome => {
|
| 232 |
+
if ("error" in outcome) throw outcome.error;
|
| 233 |
+
return loadSearchPartition(part, current, owners, outcome.packed);
|
| 234 |
+
}) : loadSearchPartition(part, current, owners);
|
| 235 |
+
// Own failures immediately, including if starting lookahead throws.
|
| 236 |
+
const valueOutcome = valuePromise.then(value => ({value}), error => ({error}));
|
| 237 |
+
const next = configuration.partitions[position + 1];
|
| 238 |
+
if (next && canPrefetchPartition(connection, next.bytes)) {
|
| 239 |
+
// Only compressed future bytes are retained. Each of the (at most
|
| 240 |
+
// two) overlapping future transfers is capped independently.
|
| 241 |
+
pending = withPartitionRequest(current, owners, signal => fetchPartitionBytes(next, signal))
|
| 242 |
+
.then(packed => ({packed}), error => ({error}));
|
| 243 |
+
}
|
| 244 |
+
const outcome = await valueOutcome;
|
| 245 |
+
if ("error" in outcome) throw outcome.error;
|
| 246 |
+
const value = outcome.value;
|
| 247 |
+
if (!current()) throw aborted();
|
| 248 |
+
// Commit counts and progress strictly in manifest order; never publish a
|
| 249 |
+
// later successful partition past a failed or unverified predecessor.
|
| 250 |
+
const local = await searchBookText(value, query, {current, yieldTask: pause});
|
| 251 |
+
if (!current()) throw aborted();
|
| 252 |
+
counts.push(local.total);
|
| 253 |
+
total += local.total;
|
| 254 |
+
if (first.length < 50) first.push(...decorate(local.page(0).results.slice(0, 50 - first.length), value.pages));
|
| 255 |
+
await progress(index, part.end, configuration.pageCount);
|
| 256 |
+
await pause();
|
| 257 |
+
}
|
| 258 |
+
complete = true;
|
| 259 |
+
return index;
|
| 260 |
+
} catch (error) {
|
| 261 |
+
// A replacement search can start before this catch resumes; abort only
|
| 262 |
+
// this search's lookahead, never another search or a result-page request.
|
| 263 |
+
for (const request of owners) request.abort();
|
| 264 |
+
throw error;
|
| 265 |
}
|
|
|
|
|
|
|
| 266 |
}
|
| 267 |
|
| 268 |
self.onmessage = async ({ data }) => {
|
|
|
|
| 271 |
active++;
|
| 272 |
session = null;
|
| 273 |
controller?.abort();
|
| 274 |
+
abortPartitionRequests();
|
| 275 |
return;
|
| 276 |
}
|
| 277 |
if (data.type !== "search" && data.type !== "page" && data.type !== "prefetch") return;
|
|
|
|
| 279 |
const current = () => token === active;
|
| 280 |
try {
|
| 281 |
if (data.type === "search") {
|
| 282 |
+
abortPartitionRequests();
|
| 283 |
session = null;
|
| 284 |
+
// Drain both search and result-page requests from the old session before
|
| 285 |
+
// starting another load, including a switch to the legacy book path.
|
| 286 |
+
await waitForPartitionRequests();
|
| 287 |
+
if (!current()) return;
|
| 288 |
const query = String(data.query || "").trim();
|
| 289 |
if (!query || query.length > 2048) throw new Error("请输入 1–2048 个字符");
|
| 290 |
if (controller?.signal.aborted && pendingBook) await pendingBook.catch(() => {});
|
tests/reader/pdf-search/test_pdf_book_worker_browser.py
CHANGED
|
@@ -8,6 +8,7 @@ import json
|
|
| 8 |
import os
|
| 9 |
from pathlib import Path
|
| 10 |
import threading
|
|
|
|
| 11 |
import unittest
|
| 12 |
import uuid
|
| 13 |
from urllib.parse import parse_qs, urlsplit
|
|
@@ -77,6 +78,8 @@ class Handler(SimpleHTTPRequestHandler):
|
|
| 77 |
self.send_error(410, 'stale test case')
|
| 78 |
return
|
| 79 |
state['active'] += 1
|
|
|
|
|
|
|
| 80 |
state['done'].clear()
|
| 81 |
try:
|
| 82 |
if state and '/'.join(parts) == state['block_path']:
|
|
@@ -96,6 +99,7 @@ class Handler(SimpleHTTPRequestHandler):
|
|
| 96 |
if state:
|
| 97 |
with self.server.state_lock:
|
| 98 |
state['active'] -= 1
|
|
|
|
| 99 |
if not state['active']:
|
| 100 |
state['done'].set()
|
| 101 |
|
|
@@ -126,7 +130,7 @@ class PdfBookWorkerBrowserTests(unittest.TestCase):
|
|
| 126 |
self.state = {
|
| 127 |
'token': uuid.uuid4().hex[:16], 'block_path': None, 'timeout': 10,
|
| 128 |
'arrived': threading.Event(), 'release': threading.Event(),
|
| 129 |
-
'done': threading.Event(), 'active': 0,
|
| 130 |
}
|
| 131 |
self.state['done'].set()
|
| 132 |
with self.server.state_lock:
|
|
@@ -235,7 +239,7 @@ class PdfBookWorkerBrowserTests(unittest.TestCase):
|
|
| 235 |
}), 'search');
|
| 236 |
}''', self.configuration())
|
| 237 |
self.assertTrue(self.state['arrived'].wait(10), 'second partition was not requested')
|
| 238 |
-
|
| 239 |
self.state['release'].set()
|
| 240 |
prefetch = page.evaluate('window.prefetchOutcome')
|
| 241 |
self.assertEqual(prefetch.get('error'), 'AbortError', f'progress prefetch unexpectedly completed: {prefetch}')
|
|
@@ -258,6 +262,166 @@ class PdfBookWorkerBrowserTests(unittest.TestCase):
|
|
| 258 |
self.assertEqual(result['page']['results'][0]['page'], 2)
|
| 259 |
self.assertEqual(page.evaluate('window.unexpected'), [])
|
| 260 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
def test_search_preempts_inflight_prefetch(self):
|
| 262 |
self.state['block_path'] = f'{BASE}/book-text.json.gz'
|
| 263 |
config = {'url': self.resource(self.state['block_path']),
|
|
|
|
| 8 |
import os
|
| 9 |
from pathlib import Path
|
| 10 |
import threading
|
| 11 |
+
import time
|
| 12 |
import unittest
|
| 13 |
import uuid
|
| 14 |
from urllib.parse import parse_qs, urlsplit
|
|
|
|
| 78 |
self.send_error(410, 'stale test case')
|
| 79 |
return
|
| 80 |
state['active'] += 1
|
| 81 |
+
state['peak'] = max(state['peak'], state['active'])
|
| 82 |
+
state['paths'].append('/'.join(parts))
|
| 83 |
state['done'].clear()
|
| 84 |
try:
|
| 85 |
if state and '/'.join(parts) == state['block_path']:
|
|
|
|
| 99 |
if state:
|
| 100 |
with self.server.state_lock:
|
| 101 |
state['active'] -= 1
|
| 102 |
+
state['completed_paths'].append('/'.join(parts))
|
| 103 |
if not state['active']:
|
| 104 |
state['done'].set()
|
| 105 |
|
|
|
|
| 130 |
self.state = {
|
| 131 |
'token': uuid.uuid4().hex[:16], 'block_path': None, 'timeout': 10,
|
| 132 |
'arrived': threading.Event(), 'release': threading.Event(),
|
| 133 |
+
'done': threading.Event(), 'active': 0, 'peak': 0, 'paths': [], 'completed_paths': [],
|
| 134 |
}
|
| 135 |
self.state['done'].set()
|
| 136 |
with self.server.state_lock:
|
|
|
|
| 239 |
}), 'search');
|
| 240 |
}''', self.configuration())
|
| 241 |
self.assertTrue(self.state['arrived'].wait(10), 'second partition was not requested')
|
| 242 |
+
page.wait_for_function('window.progressSeen === true', timeout=4000)
|
| 243 |
self.state['release'].set()
|
| 244 |
prefetch = page.evaluate('window.prefetchOutcome')
|
| 245 |
self.assertEqual(prefetch.get('error'), 'AbortError', f'progress prefetch unexpectedly completed: {prefetch}')
|
|
|
|
| 262 |
self.assertEqual(result['page']['results'][0]['page'], 2)
|
| 263 |
self.assertEqual(page.evaluate('window.unexpected'), [])
|
| 264 |
|
| 265 |
+
def test_partition_lookahead_preserves_order_progress_and_paging(self):
|
| 266 |
+
self.state['block_path'] = f'{BASE}/search-000001-000001.json.gz'
|
| 267 |
+
page = self.make_page()
|
| 268 |
+
page.evaluate('''async config => {
|
| 269 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 270 |
+
window.client=createPdfBookSearch(config);window.updates=[];
|
| 271 |
+
window.outcome=window.capture(window.client.search('needle',p=>window.updates.push({
|
| 272 |
+
scanned:p.scanned,total:p.total,pages:p.pages,first:p.results[0]?.page})), 'parallel search');
|
| 273 |
+
}''', self.configuration())
|
| 274 |
+
self.assertTrue(self.state['arrived'].wait(10), 'first partition not requested')
|
| 275 |
+
# The second request must finish while the first remains blocked;
|
| 276 |
+
# wall-clock speed is not used as the contract.
|
| 277 |
+
deadline = time.monotonic() + 4
|
| 278 |
+
while time.monotonic() < deadline:
|
| 279 |
+
with self.server.state_lock:
|
| 280 |
+
completed = list(self.state['completed_paths'])
|
| 281 |
+
if f'{BASE}/search-000002-000002.json.gz' in completed:
|
| 282 |
+
break
|
| 283 |
+
page.wait_for_timeout(20)
|
| 284 |
+
else:
|
| 285 |
+
self.fail('second partition did not complete while first was blocked')
|
| 286 |
+
self.assertEqual(page.evaluate('window.updates'), [], 'out-of-order work cannot publish past an unfinished predecessor')
|
| 287 |
+
self.state['release'].set()
|
| 288 |
+
result=page.evaluate('''async()=>{
|
| 289 |
+
const done=await window.outcome;if(!done.value)return {done};
|
| 290 |
+
const page=await window.deadline(window.client.page(100),'page');return {done,page,updates:window.updates};
|
| 291 |
+
}''')
|
| 292 |
+
self.assertEqual(result['done']['value']['total'], 180)
|
| 293 |
+
self.assertEqual(result['updates'], [dict(scanned=1,total=120,pages=2,first=1),
|
| 294 |
+
dict(scanned=2,total=180,pages=2,first=1)])
|
| 295 |
+
self.assertEqual(result['page']['offset'], 100)
|
| 296 |
+
self.assertEqual([hit['page'] for hit in result['page']['results']], [1]*20+[2]*30)
|
| 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()
|
| 303 |
+
configuration['partitions'][0]['sha256']='0'*64
|
| 304 |
+
result=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);window.updates=[];
|
| 307 |
+
const outcome=await window.capture(client.search('needle',p=>window.updates.push(p.scanned)),'failed search');
|
| 308 |
+
return {outcome,updates:window.updates};
|
| 309 |
+
}''',configuration)
|
| 310 |
+
self.assertIn('PDF_OCR_HASH_MISMATCH',result['outcome'].get('message',''))
|
| 311 |
+
self.assertEqual(result['updates'],[])
|
| 312 |
+
|
| 313 |
+
def test_failed_lookahead_waits_for_verified_predecessor(self):
|
| 314 |
+
self.state['block_path'] = f'{BASE}/search-000001-000001.json.gz'
|
| 315 |
+
configuration = self.configuration()
|
| 316 |
+
configuration['partitions'][1]['sha256'] = '0' * 64
|
| 317 |
+
page = self.make_page()
|
| 318 |
+
page.evaluate('''async config => {
|
| 319 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 320 |
+
window.client=createPdfBookSearch(config);window.updates=[];
|
| 321 |
+
window.outcome=window.capture(client.search('needle',p=>window.updates.push({
|
| 322 |
+
scanned:p.scanned,total:p.total,complete:p.complete})), 'bad lookahead');
|
| 323 |
+
}''', configuration)
|
| 324 |
+
self.assertTrue(self.state['arrived'].wait(10))
|
| 325 |
+
deadline = time.monotonic() + 4
|
| 326 |
+
while time.monotonic() < deadline:
|
| 327 |
+
with self.server.state_lock:
|
| 328 |
+
finished = f'{BASE}/search-000002-000002.json.gz' in self.state['completed_paths']
|
| 329 |
+
if finished:
|
| 330 |
+
break
|
| 331 |
+
page.wait_for_timeout(20)
|
| 332 |
+
self.assertTrue(finished, 'lookahead request did not finish')
|
| 333 |
+
self.assertEqual(page.evaluate('window.updates'), [])
|
| 334 |
+
self.state['release'].set()
|
| 335 |
+
result = page.evaluate('''async()=>({outcome:await window.outcome,updates:window.updates})''')
|
| 336 |
+
self.assertIn('PDF_OCR_HASH_MISMATCH', result['outcome'].get('message', ''))
|
| 337 |
+
self.assertEqual(result['updates'], [dict(scanned=1,total=120,complete=False)])
|
| 338 |
+
|
| 339 |
+
def test_cancel_after_legacy_prefetch_drains_partition_requests(self):
|
| 340 |
+
page = self.make_page()
|
| 341 |
+
self.state['block_path'] = f'{BASE}/search-000002-000002.json.gz'
|
| 342 |
+
configuration = self.configuration()
|
| 343 |
+
legacy = {key: configuration[key] for key in ('url', 'bytes', 'sha256', 'sourceSha')}
|
| 344 |
+
legacy['pageCount'] = 1
|
| 345 |
+
# A legacy ready Worker can receive cancel without termination; use the
|
| 346 |
+
# protocol directly to exercise cleanup before a replacement search.
|
| 347 |
+
page.evaluate('''async config => {
|
| 348 |
+
window.worker = new Worker('/static/reader/search/workers/reader-pdf-book-search-worker.mjs', {type:'module'});
|
| 349 |
+
window.workerMessages = [];
|
| 350 |
+
worker.onmessage = event => window.workerMessages.push(event.data);
|
| 351 |
+
worker.postMessage({type:'init',configuration:config});worker.postMessage({type:'prefetch',id:1});
|
| 352 |
+
}''', legacy)
|
| 353 |
+
page.wait_for_function('window.workerMessages.some(m=>m.id===1 && m.ready)', timeout=4000)
|
| 354 |
+
page.evaluate('''config => {
|
| 355 |
+
worker.postMessage({type:'init',configuration:config});worker.postMessage({type:'search',id:2,query:'needle'});
|
| 356 |
+
}''', configuration)
|
| 357 |
+
self.assertTrue(self.state['arrived'].wait(10))
|
| 358 |
+
page.wait_for_function('window.workerMessages.some(m=>m.id===2 && m.progress)', timeout=4000)
|
| 359 |
+
page.evaluate('''() => {
|
| 360 |
+
worker.postMessage({type:'cancel'});worker.postMessage({type:'search',id:3,query:'needle'});
|
| 361 |
+
}''')
|
| 362 |
+
self.state['release'].set()
|
| 363 |
+
page.wait_for_function('window.workerMessages.some(m=>m.id===3 && !m.progress)', timeout=4000)
|
| 364 |
+
result = page.evaluate('''() => {
|
| 365 |
+
const result = window.workerMessages.find(m=>m.id===3 && !m.progress);
|
| 366 |
+
worker.terminate();return result;
|
| 367 |
+
}''')
|
| 368 |
+
self.assertEqual(result.get('total'), 180)
|
| 369 |
+
self.assertEqual(len(result.get('results', [])), 50)
|
| 370 |
+
|
| 371 |
+
def test_large_lookahead_is_not_started_early(self):
|
| 372 |
+
self.state['block_path'] = f'{BASE}/search-000001-000001.json.gz'
|
| 373 |
+
configuration = self.configuration()
|
| 374 |
+
configuration['partitions'][1]['bytes'] = 1024 * 1024 + 1
|
| 375 |
+
page = self.make_page()
|
| 376 |
+
page.evaluate('''async config => {
|
| 377 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 378 |
+
window.client=createPdfBookSearch(config);
|
| 379 |
+
window.outcome=window.capture(client.search('needle'), 'large lookahead');
|
| 380 |
+
}''', configuration)
|
| 381 |
+
self.assertTrue(self.state['arrived'].wait(10))
|
| 382 |
+
page.wait_for_timeout(250)
|
| 383 |
+
with self.server.state_lock:
|
| 384 |
+
self.assertNotIn(f'{BASE}/search-000002-000002.json.gz', self.state['paths'])
|
| 385 |
+
self.state['release'].set()
|
| 386 |
+
outcome = page.evaluate('window.outcome')
|
| 387 |
+
self.assertIn('PDF_OCR_SIZE_MISMATCH', outcome.get('message', ''))
|
| 388 |
+
self.assertIn(f'{BASE}/search-000002-000002.json.gz', self.state['paths'])
|
| 389 |
+
|
| 390 |
+
def test_cancelled_partition_search_cannot_abort_replacement(self):
|
| 391 |
+
self.state['block_path']=f'{BASE}/search-000001-000001.json.gz'
|
| 392 |
+
page=self.make_page()
|
| 393 |
+
page.evaluate('''async config=>{
|
| 394 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 395 |
+
window.client=createPdfBookSearch(config);
|
| 396 |
+
window.first=window.capture(client.search('needle'),'old search');
|
| 397 |
+
}''',self.configuration())
|
| 398 |
+
self.assertTrue(self.state['arrived'].wait(10),'old request did not arrive')
|
| 399 |
+
page.evaluate('''()=>{window.second=window.capture(window.client.search('needle'),'replacement');}''')
|
| 400 |
+
self.state['release'].set()
|
| 401 |
+
result=page.evaluate('''async()=>({first:await window.first,second:await window.second})''')
|
| 402 |
+
self.assertEqual(result['first'].get('error'),'AbortError')
|
| 403 |
+
self.assertEqual(result['second']['value']['total'],180)
|
| 404 |
+
self.assertEqual(len(result['second']['value']['results']),50)
|
| 405 |
+
|
| 406 |
+
def test_cancellation_aborts_lookahead_and_retry_succeeds(self):
|
| 407 |
+
self.state['block_path']=f'{BASE}/search-000002-000002.json.gz'
|
| 408 |
+
page=self.make_page()
|
| 409 |
+
page.evaluate('''async config=>{
|
| 410 |
+
const {createPdfBookSearch}=await window.deadline(import('/static/reader/search/reader-pdf-book-search.mjs'),'import');
|
| 411 |
+
window.client=createPdfBookSearch(config);window.updates=[];
|
| 412 |
+
window.first=window.capture(client.search('needle',p=>window.updates.push(p.scanned)),'cancelled search');
|
| 413 |
+
}''',self.configuration())
|
| 414 |
+
self.assertTrue(self.state['arrived'].wait(10),'lookahead request did not arrive')
|
| 415 |
+
page.wait_for_function('window.updates.includes(1)',timeout=4000)
|
| 416 |
+
page.evaluate('window.client.cancel()')
|
| 417 |
+
self.state['release'].set()
|
| 418 |
+
result=page.evaluate('''async()=>{
|
| 419 |
+
const first=await window.first,retry=await window.capture(window.client.search('needle'),'retry');
|
| 420 |
+
return {first,retry};
|
| 421 |
+
}''')
|
| 422 |
+
self.assertEqual(result['first'].get('error'),'AbortError')
|
| 423 |
+
self.assertEqual(result['retry']['value']['total'],180)
|
| 424 |
+
|
| 425 |
def test_search_preempts_inflight_prefetch(self):
|
| 426 |
self.state['block_path'] = f'{BASE}/book-text.json.gz'
|
| 427 |
config = {'url': self.resource(self.state['block_path']),
|
tests/reader/pdf-search/test_reader_ocr_transport.mjs
CHANGED
|
@@ -63,6 +63,13 @@ const scope={self:{location:{href:'https://voiceofml-search.hf.space/static/work
|
|
| 63 |
crypto:webcrypto,performance,setTimeout,clearTimeout,fetch:async()=>new Response(packed),validateBookText,searchBookText,validPdfBookUrl,searchPath};
|
| 64 |
const context=vm.createContext(scope);
|
| 65 |
vm.runInContext(source.replace(/^import .*;\n/gm,''),context);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
await scope.self.onmessage({data:{type:'init',configuration}});
|
| 67 |
await scope.self.onmessage({data:{type:'search',id:7,query:'needle'}});
|
| 68 |
assert.equal(posted[0].bookReady,true);
|
|
|
|
| 63 |
crypto:webcrypto,performance,setTimeout,clearTimeout,fetch:async()=>new Response(packed),validateBookText,searchBookText,validPdfBookUrl,searchPath};
|
| 64 |
const context=vm.createContext(scope);
|
| 65 |
vm.runInContext(source.replace(/^import .*;\n/gm,''),context);
|
| 66 |
+
// Exercise the Worker's actual network/size policy in its existing test scope.
|
| 67 |
+
const canPrefetchPartition=vm.runInContext('canPrefetchPartition',context);
|
| 68 |
+
for(const [connection,bytes,expected] of [[undefined,1024,true],[{saveData:true},1024,false],
|
| 69 |
+
[{effectiveType:'slow-2g'},1024,false],[{effectiveType:'2g'},1024,false],
|
| 70 |
+
[{effectiveType:'3g'},1024,true],[{saveData:false,effectiveType:'4g'},1048576,true],
|
| 71 |
+
[undefined,1048577,false],[undefined,0,false],[undefined,NaN,false]])
|
| 72 |
+
assert.equal(canPrefetchPartition(connection,bytes),expected);
|
| 73 |
await scope.self.onmessage({data:{type:'init',configuration}});
|
| 74 |
await scope.self.onmessage({data:{type:'search',id:7,query:'needle'}});
|
| 75 |
assert.equal(posted[0].bookReady,true);
|