vomebook commited on
Commit
4bc2d56
·
1 Parent(s): 15a6ac1

Layer search attempts and lazy Reader index lifecycle

Browse files
backend/app.py CHANGED
@@ -58,6 +58,9 @@ from backend.search_projection import public_record as _public_record, trim_resu
58
  from backend.reader_identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,
59
  canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id)
60
  from backend.reader_index import ReaderIndexBuild, advance_build, new_build
 
 
 
61
  from backend.reader_ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,
62
  parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages)
63
  from backend.search_filters import (apply_filters as _apply_filters,
@@ -90,7 +93,7 @@ from backend.reader.document.application.ranges import (
90
  from backend.runtime.application.lifecycle import (
91
  LifecycleDependencies, LifecycleState, lifespan as _application_lifespan,
92
  )
93
- from backend.search_execution import SearchBusy, SearchExecutor, check_search_cancelled
94
  from backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnect
95
  from backend.search.application.cached import (
96
  CacheDependencies, search_cached as _search_cached, order_key as _order_key,
@@ -459,80 +462,70 @@ def build_vocab_by_len():
459
  _build_vocab_by_len(word_index, vocab_by_len)
460
 
461
 
462
- def _advance_reader_indexes(limit: int = READER_INDEX_BATCH_RECORDS, budget: float = READER_INDEX_BATCH_SECONDS) -> bool:
463
- global reader_record_indices, repo_reader_record_indices
464
- global reader_record_key_indices, reader_source_id_indices, reader_legacy_source_id_indices, _reader_indexes_ready
465
  global _reader_index_build
466
- with _reader_indexes_lock:
467
- if _reader_indexes_ready:
468
- return True
469
- if _reader_index_build is None or _reader_index_build["generation"] != _data_generation:
470
- _reader_index_build = new_build(_data_generation, records)
471
- build = _reader_index_build
472
- deadline = time.perf_counter() + budget
473
- if not advance_build(build, limit, deadline, now=time.perf_counter,
474
- source_id=reader_short_id, asset_key=build_reader_asset_key,
475
- record_link=build_record_link, dataset_url=dataset_file_url,
476
- reader_extensions=READER_EXTENSIONS):
477
- return False
478
- if build["generation"] != _data_generation or build["records"] is not records:
479
- _reader_index_build = None
480
- return False
481
- reader_record_indices = array('I', build["indices"])
482
- repo_reader_record_indices = {key: array('I', indices) for key, indices in build["repos"].items()}
483
- reader_record_key_indices = build["keys"]
484
- reader_source_id_indices = build["ids"]
485
- reader_legacy_source_id_indices = build["legacy_ids"]
486
- _reader_indexes_ready = True
487
- _reader_index_build = None
488
- return True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489
 
490
 
491
  def _build_reader_indexes():
492
- while not _advance_reader_indexes(len(records), float("inf")):
493
- pass
494
 
495
 
496
  def ensure_reader_indexes():
497
- global _reader_indexes_ready
498
- if _reader_indexes_ready:
499
- return
500
- _build_reader_indexes()
501
 
502
 
503
  async def ensure_reader_indexes_async():
504
- """Join the shared background build, or start one for an early Reader request."""
505
- if _reader_indexes_ready:
506
- return
507
- task = getattr(app.state, "reader_index_build_task", None)
508
- if task is None or task.done():
509
- async def build():
510
- while not _reader_indexes_ready:
511
- executor = getattr(app.state, "search_executor", None)
512
- if executor is None:
513
- await asyncio.to_thread(_advance_reader_indexes)
514
- else:
515
- try:
516
- await executor.run(_advance_reader_indexes, background=True)
517
- except SearchBusy:
518
- await asyncio.sleep(.02)
519
- continue
520
- await asyncio.sleep(0)
521
- task = asyncio.create_task(build())
522
- app.state.reader_index_build_task = task
523
- await asyncio.shield(task)
524
 
525
 
526
  async def warm_reader_indexes():
527
- """Prepare Reader routing during a quiet period without delaying startup."""
528
- await asyncio.sleep(READER_INDEX_WARM_DELAY_SECONDS)
529
- while not _reader_indexes_ready:
530
- while time.monotonic() - last_user_request_at < READER_INDEX_IDLE_SECONDS:
531
- await asyncio.sleep(READER_INDEX_IDLE_SECONDS)
532
- try:
533
- await ensure_reader_indexes_async()
534
- except SearchBusy:
535
- await asyncio.sleep(READER_INDEX_IDLE_SECONDS)
536
 
537
 
538
  def build_indexes(build_words: bool = True, build_reader: bool = True):
 
58
  from backend.reader_identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,
59
  canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id)
60
  from backend.reader_index import ReaderIndexBuild, advance_build, new_build
61
+ from backend.reader.catalog.application.indexes import (
62
+ IndexDependencies, IndexPublication, IndexRuntime, IndexState, ReaderIndexes,
63
+ )
64
  from backend.reader_ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,
65
  parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages)
66
  from backend.search_filters import (apply_filters as _apply_filters,
 
93
  from backend.runtime.application.lifecycle import (
94
  LifecycleDependencies, LifecycleState, lifespan as _application_lifespan,
95
  )
96
+ from backend.search_execution import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelled
97
  from backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnect
98
  from backend.search.application.cached import (
99
  CacheDependencies, search_cached as _search_cached, order_key as _order_key,
 
462
  _build_vocab_by_len(word_index, vocab_by_len)
463
 
464
 
465
+ def _set_reader_index_build(build: ReaderIndexBuild | None) -> None:
 
 
466
  global _reader_index_build
467
+ _reader_index_build = build
468
+
469
+
470
+ def _publish_reader_indexes(indexes: IndexPublication) -> None:
471
+ global reader_record_indices, repo_reader_record_indices, reader_record_key_indices
472
+ global reader_source_id_indices, reader_legacy_source_id_indices, _reader_indexes_ready
473
+ reader_record_indices = indexes.indices
474
+ repo_reader_record_indices = indexes.repos
475
+ reader_record_key_indices = indexes.keys
476
+ reader_source_id_indices = indexes.ids
477
+ reader_legacy_source_id_indices = indexes.legacy_ids
478
+ _reader_indexes_ready = True
479
+
480
+
481
+ def _new_reader_index_build(generation: int, snapshot: list[SearchRecord]) -> ReaderIndexBuild:
482
+ return new_build(generation, snapshot)
483
+
484
+
485
+ def _advance_reader_index_build(build: ReaderIndexBuild, limit: int, deadline: float) -> bool:
486
+ return advance_build(build, limit, deadline, now=time.perf_counter,
487
+ source_id=reader_short_id, asset_key=build_reader_asset_key,
488
+ record_link=build_record_link, dataset_url=dataset_file_url,
489
+ reader_extensions=READER_EXTENSIONS)
490
+
491
+
492
+ _reader_indexes = ReaderIndexes(IndexDependencies(
493
+ state=lambda: IndexState(_reader_indexes_ready, _data_generation, records, _reader_index_build),
494
+ lock=lambda: _reader_indexes_lock,
495
+ set_build=_set_reader_index_build,
496
+ publish=_publish_reader_indexes,
497
+ new_build=_new_reader_index_build,
498
+ advance_build=_advance_reader_index_build,
499
+ clock=lambda: time.perf_counter(),
500
+ runtime=lambda: cast(IndexRuntime, app.state),
501
+ advance=lambda: _advance_reader_indexes,
502
+ build_all=lambda: _build_reader_indexes(),
503
+ ensure_async=lambda: ensure_reader_indexes_async(),
504
+ monotonic=lambda: time.monotonic(),
505
+ last_request=lambda: last_user_request_at,
506
+ warm_delay=lambda: READER_INDEX_WARM_DELAY_SECONDS,
507
+ idle_seconds=lambda: READER_INDEX_IDLE_SECONDS,
508
+ ))
509
+
510
+
511
+ def _advance_reader_indexes(limit: int = READER_INDEX_BATCH_RECORDS, budget: float = READER_INDEX_BATCH_SECONDS) -> bool:
512
+ return _reader_indexes.advance(limit, budget)
513
 
514
 
515
  def _build_reader_indexes():
516
+ _reader_indexes.build()
 
517
 
518
 
519
  def ensure_reader_indexes():
520
+ _reader_indexes.ensure()
 
 
 
521
 
522
 
523
  async def ensure_reader_indexes_async():
524
+ await _reader_indexes.ensure_async()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
 
526
 
527
  async def warm_reader_indexes():
528
+ await _reader_indexes.warm()
 
 
 
 
 
 
 
 
529
 
530
 
531
  def build_indexes(build_words: bool = True, build_reader: bool = True):
backend/reader/catalog/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Reader catalog indexing and selection."""
backend/reader/catalog/application/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Reader catalog application services."""
backend/reader/catalog/application/indexes.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lazy Reader index construction, publication and shared background ownership."""
2
+
3
+ import asyncio
4
+ from array import array
5
+ from collections.abc import Awaitable, Callable, Sequence
6
+ from contextlib import AbstractContextManager
7
+ from dataclasses import dataclass
8
+ from typing import Protocol
9
+
10
+ from backend.reader_index import ReaderIndexBuild
11
+ from backend.search_execution import SearchBusy, SearchExecutor
12
+
13
+ Record = dict[str, object]
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class IndexState:
18
+ """A fresh view is required after each batch before publishing its snapshot."""
19
+
20
+ ready: bool
21
+ generation: int
22
+ records: list[Record]
23
+ build: ReaderIndexBuild | None
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class IndexPublication:
28
+ indices: Sequence[int]
29
+ repos: dict[str, Sequence[int]]
30
+ keys: dict[str, int]
31
+ ids: dict[str, list[int]]
32
+ legacy_ids: dict[str, list[int]]
33
+
34
+
35
+ class IndexRuntime(Protocol):
36
+ reader_index_build_task: asyncio.Task[None] | None
37
+ search_executor: SearchExecutor
38
+
39
+
40
+ class AdvanceIndexes(Protocol):
41
+ def __call__(self, limit: int = ..., budget: float = ...) -> bool: ...
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class IndexDependencies:
46
+ state: Callable[[], IndexState]
47
+ lock: Callable[[], AbstractContextManager[object]]
48
+ set_build: Callable[[ReaderIndexBuild | None], None]
49
+ publish: Callable[[IndexPublication], None]
50
+ new_build: Callable[[int, list[Record]], ReaderIndexBuild]
51
+ advance_build: Callable[[ReaderIndexBuild, int, float], bool]
52
+ clock: Callable[[], float]
53
+ runtime: Callable[[], IndexRuntime]
54
+ # Resolve the actual app callable at each use, including executor submission.
55
+ advance: Callable[[], AdvanceIndexes]
56
+ build_all: Callable[[], None]
57
+ ensure_async: Callable[[], Awaitable[None]]
58
+ monotonic: Callable[[], float]
59
+ last_request: Callable[[], float]
60
+ warm_delay: Callable[[], float]
61
+ idle_seconds: Callable[[], float]
62
+
63
+
64
+ class ReaderIndexes:
65
+ def __init__(self, deps: IndexDependencies) -> None:
66
+ self.deps = deps
67
+
68
+ def advance(self, limit: int, budget: float) -> bool:
69
+ deps = self.deps
70
+ with deps.lock():
71
+ state = deps.state()
72
+ if state.ready:
73
+ return True
74
+ build = state.build
75
+ if build is None or build["generation"] != state.generation:
76
+ build = deps.new_build(state.generation, state.records)
77
+ deps.set_build(build)
78
+ if not deps.advance_build(build, limit, deps.clock() + budget):
79
+ return False
80
+ current = deps.state()
81
+ if build["generation"] != current.generation or build["records"] is not current.records:
82
+ deps.set_build(None)
83
+ return False
84
+ deps.publish(IndexPublication(
85
+ array('I', build["indices"]),
86
+ {key: array('I', indices) for key, indices in build["repos"].items()},
87
+ build["keys"], build["ids"], build["legacy_ids"],
88
+ ))
89
+ deps.set_build(None)
90
+ return True
91
+
92
+ def build(self) -> None:
93
+ while not self.deps.advance()(len(self.deps.state().records), float("inf")):
94
+ pass
95
+
96
+ def ensure(self) -> None:
97
+ if not self.deps.state().ready:
98
+ self.deps.build_all()
99
+
100
+ async def ensure_async(self) -> None:
101
+ """Join one owned build; a cancelled waiter cannot cancel shared work."""
102
+ deps = self.deps
103
+ if deps.state().ready:
104
+ return
105
+ task = getattr(deps.runtime(), "reader_index_build_task", None)
106
+ if task is None or task.done():
107
+ async def build() -> None:
108
+ while not deps.state().ready:
109
+ executor = getattr(deps.runtime(), "search_executor", None)
110
+ if executor is None:
111
+ await asyncio.to_thread(deps.advance())
112
+ else:
113
+ try:
114
+ await executor.run(deps.advance(), background=True)
115
+ except SearchBusy:
116
+ await asyncio.sleep(.02)
117
+ continue
118
+ await asyncio.sleep(0)
119
+ task = asyncio.create_task(build())
120
+ deps.runtime().reader_index_build_task = task
121
+ await asyncio.shield(task)
122
+
123
+ async def warm(self) -> None:
124
+ """Wait for a quiet period before joining the regular shared build."""
125
+ deps = self.deps
126
+ await asyncio.sleep(deps.warm_delay())
127
+ while not deps.state().ready:
128
+ while deps.monotonic() - deps.last_request() < deps.idle_seconds():
129
+ await asyncio.sleep(deps.idle_seconds())
130
+ try:
131
+ await deps.ensure_async()
132
+ except SearchBusy:
133
+ await asyncio.sleep(deps.idle_seconds())
config/types/jsconfig.check.json CHANGED
@@ -85,6 +85,9 @@
85
  "../../static/reader/ui/reader-ui.mjs",
86
  "../../static/reader/ui/reader-scroll-anchor.js",
87
  "../../static/search/download-controller.js",
 
 
 
88
  "../../typings/search-downloads.d.ts",
89
  "../../static/search/downloads/application/batch.js",
90
  "../../static/search/downloads/presentation/queue.js",
 
85
  "../../static/reader/ui/reader-ui.mjs",
86
  "../../static/reader/ui/reader-scroll-anchor.js",
87
  "../../static/search/download-controller.js",
88
+ "../../typings/search-execution.d.ts",
89
+ "../../static/search/execution/domain/policy.js",
90
+ "../../static/search/execution/application/controller.js",
91
  "../../typings/search-downloads.d.ts",
92
  "../../static/search/downloads/application/batch.js",
93
  "../../static/search/downloads/presentation/queue.js",
config/types/jsconfig.search-exact.json CHANGED
@@ -26,6 +26,9 @@
26
  "../../static/search/reader-host/presentation/return-position.js",
27
  "../../static/search/reader-host/application/host.js",
28
  "../../static/search/download-controller.js",
 
 
 
29
  "../../typings/search-downloads.d.ts",
30
  "../../static/search/downloads/application/batch.js",
31
  "../../static/search/downloads/presentation/queue.js",
 
26
  "../../static/search/reader-host/presentation/return-position.js",
27
  "../../static/search/reader-host/application/host.js",
28
  "../../static/search/download-controller.js",
29
+ "../../typings/search-execution.d.ts",
30
+ "../../static/search/execution/domain/policy.js",
31
+ "../../static/search/execution/application/controller.js",
32
  "../../typings/search-downloads.d.ts",
33
  "../../static/search/downloads/application/batch.js",
34
  "../../static/search/downloads/presentation/queue.js",
config/types/jsconfig.strict.json CHANGED
@@ -79,6 +79,9 @@
79
  "../../static/search/reader-host/presentation/return-position.js",
80
  "../../static/search/reader-host/application/host.js",
81
  "../../static/search/download-controller.js",
 
 
 
82
  "../../typings/search-downloads.d.ts",
83
  "../../static/search/downloads/application/batch.js",
84
  "../../static/search/downloads/presentation/queue.js",
 
79
  "../../static/search/reader-host/presentation/return-position.js",
80
  "../../static/search/reader-host/application/host.js",
81
  "../../static/search/download-controller.js",
82
+ "../../typings/search-execution.d.ts",
83
+ "../../static/search/execution/domain/policy.js",
84
+ "../../static/search/execution/application/controller.js",
85
  "../../typings/search-downloads.d.ts",
86
  "../../static/search/downloads/application/batch.js",
87
  "../../static/search/downloads/presentation/queue.js",
eslint.config.mjs CHANGED
@@ -40,7 +40,7 @@ export default [
40
  bytesToDisplay: "readonly", fmtSizeUrl: "readonly", parseSizeStr: "readonly", formatSize: "readonly",
41
  buildRecordRelativePath: "readonly", encodeRecordPath: "readonly",
42
  escapeHTML: "readonly", getHighlightRegex: "readonly", highlightText: "readonly", BoundedResponseCache: "readonly", VoiceOfMLSearchFileTypes: "readonly", VoiceOfMLSearchValidation: "readonly", VoiceOfMLSearchIdentity: "readonly",
43
- VoiceOfMLSidebarFilterList: "readonly", VoiceOfMLSidebarFolderTree: "readonly", VoiceOfMLSidebarFilters: "readonly", VoiceOfMLSidebarScroll: "readonly", VoiceOfMLSidebarDirectoryView: "readonly", VoiceOfMLSidebarDirectory: "readonly", VoiceOfMLSearchFolderSelection: "readonly", VoiceOfMLSearchHeightIndex: "readonly", VoiceOfMLSearchCanonical: "readonly", VoiceOfMLSearchViewKey: "readonly", VoiceOfMLSearchRecovery: "readonly", VoiceOfMLSearchWindowPage: "readonly", VoiceOfMLSearchSidebarRender: "readonly", VoiceOfMLSearchInput: "readonly", VoiceOfMLSearchInputOwnership: "readonly", VoiceOfMLPagingPolicy: "readonly", VoiceOfMLPagingController: "readonly", VoiceOfMLPagingStatus: "readonly", VoiceOfMLSearchTransport: "readonly", VoiceOfMLSearchPrefetch: "readonly", VoiceOfMLResultWindowLoader: "readonly", VoiceOfMLResultWindowStatus: "readonly"
44
  } } },
45
  { files: ["static/**/*.mjs", "static/**/reader.js", "static/**/reader-pdf-text.js", "static/**/reader-book-text.js"],
46
  languageOptions: { sourceType: "module" } },
 
40
  bytesToDisplay: "readonly", fmtSizeUrl: "readonly", parseSizeStr: "readonly", formatSize: "readonly",
41
  buildRecordRelativePath: "readonly", encodeRecordPath: "readonly",
42
  escapeHTML: "readonly", getHighlightRegex: "readonly", highlightText: "readonly", BoundedResponseCache: "readonly", VoiceOfMLSearchFileTypes: "readonly", VoiceOfMLSearchValidation: "readonly", VoiceOfMLSearchIdentity: "readonly",
43
+ VoiceOfMLSidebarFilterList: "readonly", VoiceOfMLSidebarFolderTree: "readonly", VoiceOfMLSidebarFilters: "readonly", VoiceOfMLSidebarScroll: "readonly", VoiceOfMLSidebarDirectoryView: "readonly", VoiceOfMLSidebarDirectory: "readonly", VoiceOfMLSearchFolderSelection: "readonly", VoiceOfMLSearchHeightIndex: "readonly", VoiceOfMLSearchCanonical: "readonly", VoiceOfMLSearchViewKey: "readonly", VoiceOfMLSearchRecovery: "readonly", VoiceOfMLSearchWindowPage: "readonly", VoiceOfMLSearchSidebarRender: "readonly", VoiceOfMLSearchInput: "readonly", VoiceOfMLSearchInputOwnership: "readonly", VoiceOfMLPagingPolicy: "readonly", VoiceOfMLPagingController: "readonly", VoiceOfMLPagingStatus: "readonly", VoiceOfMLSearchTransport: "readonly", VoiceOfMLSearchPrefetch: "readonly", VoiceOfMLSearchExecution: "readonly", VoiceOfMLSearchExecutionPolicy: "readonly", VoiceOfMLResultWindowLoader: "readonly", VoiceOfMLResultWindowStatus: "readonly"
44
  } } },
45
  { files: ["static/**/*.mjs", "static/**/reader.js", "static/**/reader-pdf-text.js", "static/**/reader-book-text.js"],
46
  languageOptions: { sourceType: "module" } },
pyrightconfig.strict.json CHANGED
@@ -65,6 +65,9 @@
65
  "backend/search_bootstrap.py",
66
  "backend/reader_archive.py",
67
  "backend/reader/__init__.py",
 
 
 
68
  "backend/reader/archive/__init__.py",
69
  "backend/reader/archive/application/__init__.py",
70
  "backend/reader/archive/application/archives.py",
 
65
  "backend/search_bootstrap.py",
66
  "backend/reader_archive.py",
67
  "backend/reader/__init__.py",
68
+ "backend/reader/catalog/__init__.py",
69
+ "backend/reader/catalog/application/__init__.py",
70
+ "backend/reader/catalog/application/indexes.py",
71
  "backend/reader/archive/__init__.py",
72
  "backend/reader/archive/application/__init__.py",
73
  "backend/reader/archive/application/archives.py",
scripts/build/check_reader_release.mjs CHANGED
@@ -247,6 +247,8 @@ function crossCheck(githubRoot, hfRoot) {
247
  "reader/search/reader-pdf-book-search.mjs",
248
  "search/search-session.js",
249
  "search/download-controller.js",
 
 
250
  "search/downloads/application/batch.js",
251
  "search/downloads/presentation/queue.js",
252
  "search/size-format.js",
 
247
  "reader/search/reader-pdf-book-search.mjs",
248
  "search/search-session.js",
249
  "search/download-controller.js",
250
+ "search/execution/domain/policy.js",
251
+ "search/execution/application/controller.js",
252
  "search/downloads/application/batch.js",
253
  "search/downloads/presentation/queue.js",
254
  "search/size-format.js",
scripts/build/compose_app.mjs CHANGED
@@ -9,6 +9,7 @@ export const APP_DEPENDENCIES = Object.freeze([
9
  "search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
10
  "search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js",
11
  "search/results/snapshots/domain/copy-budget.js", "search/results/snapshots/application/store.js",
 
12
  "search/search-session.js", "search/download-controller.js", "search/downloads/application/batch.js", "search/downloads/presentation/queue.js", "search/size-format.js", "search/record-path.js",
13
  "search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js",
14
  "search/input/domain/ownership.js", "search/input/application/controller.js",
 
9
  "search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js",
10
  "search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js",
11
  "search/results/snapshots/domain/copy-budget.js", "search/results/snapshots/application/store.js",
12
+ "search/execution/domain/policy.js", "search/execution/application/controller.js",
13
  "search/search-session.js", "search/download-controller.js", "search/downloads/application/batch.js", "search/downloads/presentation/queue.js", "search/size-format.js", "search/record-path.js",
14
  "search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js",
15
  "search/input/domain/ownership.js", "search/input/application/controller.js",
static/app.js CHANGED
@@ -3492,8 +3492,6 @@ async function doSearch(append = false, fromStart = false, restorePosition = fal
3492
  if (!append) setSearchVisualLoading(true);
3493
  STATE._pendingPage = STATE.page;
3494
  const currentRequestId = ++searchRequestId;
3495
- let pagingSucceeded = false;
3496
- let pagingError = null;
3497
  const requestBody = Object.assign(buildCurrentSearchBody(STATE.page), { signal: searchAbortController.signal });
3498
  STATE.resultsSkeletonActive = shouldShowResultsSkeleton(append);
3499
  DOM.resultsLoading.style.display = (!append && STATE.results.length > 0) ? 'none' : ((!append && !STATE.resultsSkeletonActive) ? 'flex' : 'none');
@@ -3506,55 +3504,35 @@ async function doSearch(append = false, fromStart = false, restorePosition = fal
3506
  clearResultsSkeleton();
3507
  }
3508
  }
3509
- try {
3510
- const data = await API.search(requestBody);
3511
- if (currentRequestId !== searchRequestId) return;
3512
- if (!applySearchPage(data, append)) {
3513
- DOM.resultsLoading.style.display = 'none';
3514
- return;
3515
- }
3516
- if (append) {
3517
- refreshVirtualAfterAppend();
3518
- } else {
3519
- DOM.resultsContainer.scrollTop = 0;
3520
- backToTopPending = false;
3521
- resetVirtualScrollState();
3522
- renderResults(true);
3523
- }
3524
- STATE.page = STATE._loadedPage;
3525
- pagingSucceeded = true;
3526
- updateStatusBar();
3527
- updateLoadInfo();
3528
- syncStateToURL(true);
3529
- prefetchNextPage();
3530
- warmConnection();
3531
- } catch (err) {
3532
- if (currentRequestId !== searchRequestId) return;
3533
- if (append && currentRequestId === searchRequestId) {
3534
- STATE.page = Math.max(1, STATE._loadedPage);
3535
- }
3536
- if (err.name === 'AbortError') return;
3537
- pagingError = err;
3538
- if (!append) STATE.hasMore = true;
3539
- console.error('搜索失败:', err);
3540
- if (!append && !recoveringFirstPage) showToast('搜索失败');
3541
- } finally {
3542
- if (currentRequestId === searchRequestId) {
3543
- STATE._pendingPage = 0;
3544
- STATE.isLoading = false;
3545
- STATE.resultsSkeletonActive = false;
3546
- DOM.resultsLoading.style.display = 'none';
3547
- if (!append) setSearchVisualLoading(false);
3548
- else updateStatusBar();
3549
- if (!append && backToTopPending) {
3550
  backToTopPending = false;
3551
- updateSearchPositionControls();
 
3552
  }
3553
- if (!append) DOM.resultsList.classList.remove("results-pending");
3554
- if ((append || recoveringFirstPage || pagingError) && (pagingSucceeded || pagingError)) finishPagingAttempt(pagingSucceeded, pagingError);
3555
- else updatePagingStatus();
3556
- }
3557
- }
 
 
 
 
 
 
 
3558
  }
3559
 
3560
  // Filter feature composition: only filter state and effects cross this boundary.
 
3492
  if (!append) setSearchVisualLoading(true);
3493
  STATE._pendingPage = STATE.page;
3494
  const currentRequestId = ++searchRequestId;
 
 
3495
  const requestBody = Object.assign(buildCurrentSearchBody(STATE.page), { signal: searchAbortController.signal });
3496
  STATE.resultsSkeletonActive = shouldShowResultsSkeleton(append);
3497
  DOM.resultsLoading.style.display = (!append && STATE.results.length > 0) ? 'none' : ((!append && !STATE.resultsSkeletonActive) ? 'flex' : 'none');
 
3504
  clearResultsSkeleton();
3505
  }
3506
  }
3507
+ return getSearchExecution().execute(requestBody, append, recoveringFirstPage, currentRequestId);
3508
+ }
3509
+
3510
+ var searchExecution;
3511
+ function getSearchExecution() {
3512
+ return searchExecution ||= VoiceOfMLSearchExecution.create({
3513
+ readView: () => ({ requestId: searchRequestId, loadedPage: STATE._loadedPage }),
3514
+ update: patch => { Object.assign(STATE, patch); },
3515
+ search: body => API.search(body), applyPage: (data, append) => applySearchPage(data, append),
3516
+ renderPage: append => {
3517
+ if (append) refreshVirtualAfterAppend();
3518
+ else {
3519
+ DOM.resultsContainer.scrollTop = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3520
  backToTopPending = false;
3521
+ resetVirtualScrollState();
3522
+ renderResults(true);
3523
  }
3524
+ },
3525
+ hideLoading: () => { DOM.resultsLoading.style.display = "none"; },
3526
+ visualLoading: value => setSearchVisualLoading(value),
3527
+ finishPresentation: () => {
3528
+ if (backToTopPending) { backToTopPending = false; updateSearchPositionControls(); }
3529
+ DOM.resultsList.classList.remove("results-pending");
3530
+ },
3531
+ updateStatus: () => updateStatusBar(), updateLoadInfo: () => updateLoadInfo(),
3532
+ syncURL: () => syncStateToURL(true), prefetch: () => prefetchNextPage(), warmConnection: () => warmConnection(),
3533
+ notify: message => showToast(message),
3534
+ finishPaging: (ok, error) => finishPagingAttempt(ok, error), updatePaging: () => updatePagingStatus(),
3535
+ });
3536
  }
3537
 
3538
  // Filter feature composition: only filter state and effects cross this boundary.
static/index.html CHANGED
@@ -347,6 +347,8 @@ if ("serviceWorker" in navigator) {
347
  <script src="/static/search/results/snapshots/application/store.js"></script>
348
  <script src="/static/search/search-session.js"></script>
349
  <script src="/static/search/download-controller.js"></script>
 
 
350
  <script src="/static/search/downloads/application/batch.js"></script>
351
  <script src="/static/search/downloads/presentation/queue.js"></script>
352
  <script src="/static/search/size-format.js"></script>
 
347
  <script src="/static/search/results/snapshots/application/store.js"></script>
348
  <script src="/static/search/search-session.js"></script>
349
  <script src="/static/search/download-controller.js"></script>
350
+ <script src="/static/search/execution/domain/policy.js"></script>
351
+ <script src="/static/search/execution/application/controller.js"></script>
352
  <script src="/static/search/downloads/application/batch.js"></script>
353
  <script src="/static/search/downloads/presentation/queue.js"></script>
354
  <script src="/static/search/size-format.js"></script>
static/reader-resources.js CHANGED
@@ -245,6 +245,8 @@
245
  ...readerFiles,
246
  "search/search-session.js",
247
  "search/download-controller.js",
 
 
248
  "search/downloads/application/batch.js",
249
  "search/downloads/presentation/queue.js",
250
  "search/size-format.js",
 
245
  ...readerFiles,
246
  "search/search-session.js",
247
  "search/download-controller.js",
248
+ "search/execution/domain/policy.js",
249
+ "search/execution/application/controller.js",
250
  "search/downloads/application/batch.js",
251
  "search/downloads/presentation/queue.js",
252
  "search/size-format.js",
static/search/execution/application/controller.js ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Owns the API attempt and completion. The host publishes request ownership
2
+ // synchronously after cancellation, cache consumption and position preparation.
3
+ (function () {
4
+ /** @param {SearchExecutionDependencies} deps */
5
+ function create(deps) {
6
+ /** @param {VoiceOfMLSearchRequestBody} requestBody @param {boolean} append @param {boolean} recoveringFirstPage @param {number} requestId */
7
+ async function execute(requestBody, append, recoveringFirstPage, requestId) {
8
+ const current = () => requestId === deps.readView().requestId;
9
+ let pagingSucceeded = false;
10
+ let pagingError = null;
11
+ try {
12
+ const data = await deps.search(requestBody);
13
+ if (!current()) return;
14
+ if (!deps.applyPage(data, append)) {
15
+ deps.hideLoading();
16
+ return;
17
+ }
18
+ deps.renderPage(append);
19
+ deps.update({ page: deps.readView().loadedPage });
20
+ pagingSucceeded = true;
21
+ deps.updateStatus();
22
+ deps.updateLoadInfo();
23
+ deps.syncURL();
24
+ deps.prefetch();
25
+ deps.warmConnection();
26
+ } catch (error) {
27
+ const err = /** @type {Error} */ (error);
28
+ if (!current()) return;
29
+ if (append) deps.update({ page: Math.max(1, deps.readView().loadedPage) });
30
+ if (err.name === "AbortError") return;
31
+ pagingError = err;
32
+ if (!append) deps.update({ hasMore: true });
33
+ console.error("搜索失败:", err);
34
+ if (!append && !recoveringFirstPage) deps.notify("搜索失败");
35
+ } finally {
36
+ if (current()) {
37
+ deps.update({ _pendingPage: 0, isLoading: false, resultsSkeletonActive: false });
38
+ deps.hideLoading();
39
+ if (!append) deps.visualLoading(false);
40
+ else deps.updateStatus();
41
+ if (!append) deps.finishPresentation();
42
+ if (globalThis.VoiceOfMLSearchExecutionPolicy.finishPaging(append, recoveringFirstPage, pagingSucceeded, pagingError)) deps.finishPaging(pagingSucceeded, pagingError);
43
+ else deps.updatePaging();
44
+ }
45
+ }
46
+ }
47
+ return { execute };
48
+ }
49
+ globalThis.VoiceOfMLSearchExecution = { create };
50
+ })();
static/search/execution/domain/policy.js ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ (function () {
2
+ // A failed first-page recovery participates in paging retry just like append.
3
+ /** @param {boolean} append @param {boolean} recoveringFirstPage @param {boolean} succeeded @param {unknown} error */
4
+ function finishPaging(append, recoveringFirstPage, succeeded, error) {
5
+ return !!((append || recoveringFirstPage || error) && (succeeded || error));
6
+ }
7
+ globalThis.VoiceOfMLSearchExecutionPolicy = { finishPaging };
8
+ })();
static/sw.js CHANGED
@@ -116,6 +116,8 @@ const PRECACHE_URLS = [
116
  "/static/search/results/presentation/paging-status.js",
117
  "/static/search/results/window/application/page-loader.js",
118
  "/static/search/results/window/presentation/status.js",
 
 
119
  "/static/search/downloads/application/batch.js",
120
  "/static/search/downloads/presentation/queue.js",
121
  "/static/app.js",
 
116
  "/static/search/results/presentation/paging-status.js",
117
  "/static/search/results/window/application/page-loader.js",
118
  "/static/search/results/window/presentation/status.js",
119
+ "/static/search/execution/domain/policy.js",
120
+ "/static/search/execution/application/controller.js",
121
  "/static/search/downloads/application/batch.js",
122
  "/static/search/downloads/presentation/queue.js",
123
  "/static/app.js",
tests/reader/backend/test_reader_index_warming.py CHANGED
@@ -181,6 +181,48 @@ class ReaderIndexWarmingTests(unittest.IsolatedAsyncioTestCase):
181
  self.assertEqual(list(app.reader_record_indices), list(range(700)))
182
  self.assertIsNone(app._reader_index_build)
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  async def test_rebuild_discards_partial_old_corpus(self):
185
  app.records *= 10
186
  self.assertFalse(app._advance_reader_indexes(limit=1))
 
181
  self.assertEqual(list(app.reader_record_indices), list(range(700)))
182
  self.assertIsNone(app._reader_index_build)
183
 
184
+ async def test_batch_defaults_remain_captured_when_policy_constants_change(self):
185
+ captured_limit, captured_budget = app._advance_reader_indexes.__defaults__
186
+ app.records *= captured_limit + 1
187
+ app.build_indexes(build_words=False, build_reader=False)
188
+ with mock.patch.object(app, 'READER_INDEX_BATCH_RECORDS', 1), \
189
+ mock.patch.object(app, 'READER_INDEX_BATCH_SECONDS', -1), \
190
+ mock.patch.object(app.time, 'perf_counter', return_value=0):
191
+ self.assertGreater(captured_budget, 0)
192
+ self.assertFalse(app._advance_reader_indexes())
193
+ self.assertEqual(app._reader_index_build['next'], captured_limit)
194
+ self.assertFalse(app._reader_indexes_ready)
195
+ self.assertEqual(app.reader_record_indices, [])
196
+
197
+ async def test_warm_rechecks_idle_policy_and_ensure_hook_after_waits(self):
198
+ sleeps = []
199
+ first_ensure = mock.AsyncMock(side_effect=app.SearchBusy())
200
+
201
+ async def finish():
202
+ app._reader_indexes_ready = True
203
+
204
+ replacement = mock.AsyncMock(side_effect=finish)
205
+
206
+ async def sleep(delay):
207
+ sleeps.append(delay)
208
+ if len(sleeps) == 2:
209
+ app.last_user_request_at = 0
210
+ app.READER_INDEX_IDLE_SECONDS = 7
211
+ elif len(sleeps) == 3:
212
+ app.ensure_reader_indexes_async = replacement
213
+
214
+ with mock.patch.object(app, 'READER_INDEX_WARM_DELAY_SECONDS', 2), \
215
+ mock.patch.object(app, 'READER_INDEX_IDLE_SECONDS', 3), \
216
+ mock.patch.object(app, 'last_user_request_at', 100), \
217
+ mock.patch.object(app.time, 'monotonic', return_value=100), \
218
+ mock.patch.object(app, 'ensure_reader_indexes_async', first_ensure), \
219
+ mock.patch.object(app.asyncio, 'sleep', side_effect=sleep):
220
+ await app.warm_reader_indexes()
221
+ self.assertEqual(sleeps, [2, 3, 7])
222
+ first_ensure.assert_awaited_once_with()
223
+ replacement.assert_awaited_once_with()
224
+ self.assertTrue(app._reader_indexes_ready)
225
+
226
  async def test_rebuild_discards_partial_old_corpus(self):
227
  app.records *= 10
228
  self.assertFalse(app._advance_reader_indexes(limit=1))
tests/support/classic_search_modules.js CHANGED
@@ -5,7 +5,7 @@ const fs = require("fs");
5
  const path = require("path");
6
  const vm = require("vm");
7
 
8
- const MODULES = ["static/search/downloads/application/batch.js", "static/search/downloads/presentation/queue.js", "static/search/presentation/sidebar-render.js", "static/search/sidebar/infrastructure/scroll.js", "static/search/sidebar/presentation/directory.js", "static/search/sidebar/application/directory.js", "static/search/search-session.js", "static/search/domain/search-window-page.js",
9
  "static/search/positions/domain/policy.js", "static/search/positions/infrastructure/indexed-db.js", "static/search/positions/application/persistence.js",
10
  "static/search/results/snapshots/domain/copy-budget.js", "static/search/results/snapshots/application/store.js",
11
  "static/search/folder-selection.js", "static/search/domain/height-index.js",
 
5
  const path = require("path");
6
  const vm = require("vm");
7
 
8
+ const MODULES = ["static/search/execution/domain/policy.js", "static/search/execution/application/controller.js", "static/search/downloads/application/batch.js", "static/search/downloads/presentation/queue.js", "static/search/presentation/sidebar-render.js", "static/search/sidebar/infrastructure/scroll.js", "static/search/sidebar/presentation/directory.js", "static/search/sidebar/application/directory.js", "static/search/search-session.js", "static/search/domain/search-window-page.js",
9
  "static/search/positions/domain/policy.js", "static/search/positions/infrastructure/indexed-db.js", "static/search/positions/application/persistence.js",
10
  "static/search/results/snapshots/domain/copy-budget.js", "static/search/results/snapshots/application/store.js",
11
  "static/search/folder-selection.js", "static/search/domain/height-index.js",
typings/search-execution.d.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ interface SearchExecutionPatch {
2
+ page?: number; _pendingPage?: number; hasMore?: boolean;
3
+ isLoading?: boolean; resultsSkeletonActive?: boolean;
4
+ }
5
+ interface SearchExecutionDependencies {
6
+ readView(): {requestId: number; loadedPage: number}; update(patch: SearchExecutionPatch): void;
7
+ search(body: VoiceOfMLSearchRequestBody): Promise<VoiceOfMLSearchWindowPageData>;
8
+ applyPage(data: VoiceOfMLSearchWindowPageData, append: boolean): boolean;
9
+ renderPage(append: boolean): void; hideLoading(): void; visualLoading(value: boolean): void;
10
+ finishPresentation(): void; updateStatus(): void; updateLoadInfo(): void;
11
+ syncURL(): void; prefetch(): void; warmConnection(): void; notify(message: string): void;
12
+ finishPaging(ok: boolean, error: unknown): void; updatePaging(): void;
13
+ }
14
+ declare var VoiceOfMLSearchExecutionPolicy: {
15
+ finishPaging(append: boolean, recoveringFirstPage: boolean, succeeded: boolean, error: unknown): boolean;
16
+ };
17
+ declare var VoiceOfMLSearchExecution: { create(deps: SearchExecutionDependencies): {
18
+ execute(body: VoiceOfMLSearchRequestBody, append: boolean, recoveringFirstPage: boolean, requestId: number): Promise<void>;
19
+ }};