diff --git a/backend/app.py b/backend/app.py index 82f220539621d42743b2efb3aeb2f9c480f158c2..d2a89d4b4e83c618b4aa82766f25fd3e3c28fe04 100644 --- a/backend/app.py +++ b/backend/app.py @@ -31,7 +31,7 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from starlette.types import Scope from contextlib import asynccontextmanager -from backend.cache_core import cached as _bounded_cache +from backend.shared.cache.core import cached as _bounded_cache from backend.catalog.application.metadata import ( CatalogMetadata, RepoSummary as RepoSummary, load_sidebar_payload as load_sidebar_payload, ) @@ -45,18 +45,18 @@ from backend.download.http.routes import ( DownloadDependencies, DownloadState, download as _download, download_check as _download_check, download_with_disconnect as _download_with_disconnect, ) -from backend.download_warm import (warm_download_connection as _warm_download_connection, +from backend.download.application.warming import (warm_download_connection as _warm_download_connection, schedule_download_connection_warm as _schedule_download_connection_warm) -from backend.folder_tree import build_folder_tree as _build_folder_tree -from backend.folder_contents import get_folder_contents as _get_folder_contents -from backend.search_bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results -from backend.search_candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates -from backend.search_browse import browse_order as _browse_order -from backend.search_term_candidates import term_candidates as _search_term_candidates -from backend.search_projection import public_record as _public_record, trim_results as _trim_results -from backend.reader_identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE, +from backend.search.corpus.domain.folder_tree import build_folder_tree as _build_folder_tree +from backend.search.corpus.domain.folder_contents import get_folder_contents as _get_folder_contents +from backend.search.application.bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results +from backend.search.domain.candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates +from backend.search.domain.browse import browse_order as _browse_order +from backend.search.domain.term_candidates import term_candidates as _search_term_candidates +from backend.search.domain.projection import public_record as _public_record, trim_results as _trim_results +from backend.reader.query.domain.identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE, canonical_reader_source_url as canonical_reader_source_url, reader_short_id as reader_short_id) -from backend.reader_index import ReaderIndexBuild, advance_build, new_build +from backend.reader.catalog.domain.index import ReaderIndexBuild, advance_build, new_build from backend.reader.catalog.application.indexes import ( IndexDependencies, IndexPublication, IndexRuntime, IndexState, ReaderIndexes, ) @@ -74,21 +74,21 @@ from backend.reader.query.http.routes import ( QueryStream, reader_resolve as _query_resolve, reader_content as _query_content, reader_ocr_search as _query_ocr_search, ) -from backend.reader_ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text, +from backend.reader.query.domain.ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text, parse_reader_ocr_book as _parse_reader_ocr_book, search_reader_ocr_pages as search_reader_ocr_pages) -from backend.search_filters import (apply_filters as _apply_filters, +from backend.search.domain.filters import (apply_filters as _apply_filters, apply_mixed_folder_filters as _apply_mixed_folder_filters, mixed_folder_index_candidates as _mixed_folder_index_candidates, score_record as _score_record) -from backend.search_words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index, +from backend.search.corpus.domain.words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index, matches_file_query as _matches_file_query, matches_file_token as _matches_file_token, records_digest as _records_digest, tokenize as _tokenize) -from backend.search_matching import (compile_exact_matcher as compile_exact_matcher, +from backend.search.domain.matching import (compile_exact_matcher as compile_exact_matcher, split_exact_terms as split_exact_terms, edit_distance as edit_distance, could_be_fuzzy as could_be_fuzzy, is_fuzzy_match as is_fuzzy_match) -from backend.proxy_streams import ( +from backend.shared.transport.streams import ( OwnedStreamingResponse as OwnedStreamingResponse, SharedRangeFlight as SharedRangeFlight, UpstreamLease, ) -from backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange, +from backend.reader.document.domain.range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange, requested_range_bounds as _requested_range_bounds) from backend.reader.document.domain.policy import ( RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry, RangeFlightKey as RangeFlightKey, @@ -106,7 +106,7 @@ from backend.reader.document.application.ranges import ( from backend.runtime.application.lifecycle import ( LifecycleDependencies, LifecycleState, lifespan as _application_lifespan, ) -from backend.search_execution import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelled +from backend.search.infrastructure.executor import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelled from backend.search.application.execution import run_search_with_disconnect as _run_search_with_disconnect from backend.search.application.cached import ( CacheDependencies, search_cached as _search_cached, order_key as _order_key, @@ -131,24 +131,24 @@ from backend.search.corpus.application.preparation import ( from backend.search.corpus.domain.metadata import ( MetadataMaps, populate_metadata, name_order, size_order, pack_postings, ) -from backend.search_transport import SearchBodyLimitMiddleware -from backend.search_indexes import ( +from backend.search.http.body_limit import SearchBodyLimitMiddleware +from backend.search.corpus.infrastructure.indexes import ( NGRAM_MAGIC as NGRAM_MAGIC, WORD_INDEX_MAGIC as WORD_INDEX_MAGIC, WORD_INDEX_TOKENIZER as WORD_INDEX_TOKENIZER, Posting, PostingIndex, decode_postings as decode_postings, decode_varint as decode_varint, load_ngram_index, load_word_index, resolve_postings, ) -from backend.reader_assets import ( +from backend.reader.catalog.domain.assets import ( READER_ASSET_FILENAMES as READER_ASSET_FILENAMES, READER_BUCKET_PATH_RE, decode_reader_assets, ) -from backend.reader_v3_catalog import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecar -from backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell -from backend.data_formats import ( +from backend.reader.catalog.infrastructure.v3 import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecar +from backend.site.application.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell +from backend.search.corpus.domain.formats import ( decode_browser_entry as decode_browser_entry, decode_folder_browser_data as decode_folder_browser_data, decode_folder_tree_data as decode_folder_tree_data, decode_search_payload as decode_search_payload, decode_tree_node as decode_tree_node, ) -from backend.record_metadata import ( +from backend.search.corpus.domain.records import ( READER_ASSET_MODES as READER_ASSET_MODES, add_reader_assets, build_browser_file_name as build_browser_file_name, build_reader_asset_key, build_record_link, build_record_path_url, build_record_relative_path, @@ -156,7 +156,7 @@ from backend.record_metadata import ( reader_asset_url as reader_asset_url, reader_extension_for_asset as reader_extension_for_asset, reader_resolved_record, ) -from backend.upstream_http import ( +from backend.shared.transport.upstream import ( ALLOWED_DOWNLOAD_HOSTS as ALLOWED_DOWNLOAD_HOSTS, ALLOWED_DOWNLOAD_HOST_SUFFIXES as ALLOWED_DOWNLOAD_HOST_SUFFIXES, MAX_REDIRECTS as MAX_REDIRECTS, READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, VOICEOFML_READER_SOURCE_RE as VOICEOFML_READER_SOURCE_RE, diff --git a/backend/cache_core.py b/backend/cache_core.py index c22dff744744021fd494a54fa6e31eab95cee137..82f93794dcf8486f9a5d349e6880be111f23cdbc 100644 --- a/backend/cache_core.py +++ b/backend/cache_core.py @@ -1,31 +1,8 @@ -"""Bounded insertion-ordered response cache shared by API and search.""" -from collections.abc import Callable, Hashable -import json -import time - - -def cached(store: dict[Hashable, tuple[float, object] | tuple[float, object, int]], key: Hashable, - builder: Callable[[], object], ttl: float, limit: int, *, - max_entry_bytes: int, max_total_bytes: int) -> object: - now = time.monotonic() - cached = store.get(key) - if cached and now - cached[0] < ttl: - store[key] = store.pop(key) - return cached[1] - value = builder() - store.pop(key, None) - for old_key, entry in list(store.items()): - if now - entry[0] >= ttl: - del store[old_key] - size = (len(value) if isinstance(value, bytes) else len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))) + len(str(key).encode("utf-8")) - if size > max_entry_bytes: - return value - total = sum(entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) for entry in store.values()) - while store and (len(store) >= limit or total + size > max_total_bytes): - oldest_key = next(iter(store)) - entry = store.pop(oldest_key) - total -= entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) - if size <= max_total_bytes: - store[key] = (now, value, size) - return value +"""Compatibility import for backend.shared.cache.core.""" +import sys +from backend.shared.cache import core as _implementation +from backend.shared.cache.core import ( + cached as cached, +) +sys.modules[__name__] = _implementation diff --git a/backend/data_formats.py b/backend/data_formats.py index 277d55a05535a4d9505231ac5f04813c5ff44a20..d31c349e4aab51597fc04b8d2676ea75f5edc2d5 100644 --- a/backend/data_formats.py +++ b/backend/data_formats.py @@ -1,110 +1,17 @@ -"""Decode the current compact corpus and directory formats without runtime state.""" - -from typing import TypedDict, cast - - -class CompactCorpus(TypedDict, total=False): - rp: list[str] - fd: list[list[str]] - rc: list[object] - - -class CompactTreeNode(TypedDict, total=False): - n: str - c: int - df: bool - ch: list["CompactTreeNode"] - - -class CompactFolder(TypedDict, total=False): - n: str - c: int - - -class CompactFile(TypedDict, total=False): - n: str - e: str - t: bool - s: int | str - - -class CompactBrowserEntry(TypedDict, total=False): - d: list[CompactFolder] - f: list[CompactFile] - - -def decode_search_payload(data: object) -> list[dict[str, object]]: - if not isinstance(data, dict): - return [] - compact = cast(CompactCorpus, data) - repos = compact.get("rp", []) or [] - folders = compact.get("fd", []) or [] - records: list[dict[str, object]] = [] - for raw_item in compact.get("rc", []) or []: - if not isinstance(raw_item, list): - continue - item = cast(list[object], raw_item) - if len(item) < 6: - continue - repo = repos[item[0]] if isinstance(item[0], int) and 0 <= item[0] < len(repos) else "" - folder = folders[item[3]] if isinstance(item[3], int) and 0 <= item[3] < len(folders) else [] - records.append({ - "Repo": repo, - "File": item[1], - "Extension": item[2], - "Folder": folder, - "Size": item[4], - "HasTxt": bool(item[5]), - }) - return records - - -def decode_tree_node(node: CompactTreeNode, parent_path: str = "", is_root: bool = False) -> dict[str, object]: - name = node.get("n", "") - path = "" if is_root else (f"{parent_path}/{name}" if parent_path else name) - children = [decode_tree_node(child, path, False) for child in node.get("ch", [])] - decoded: dict[str, object] = { - "name": name, - "path": path, - "count": node.get("c", 0), - "hasDirectFiles": node.get("df", False), - "hasChildren": len(children) > 0, - "showSelfToggle": bool(path and node.get("df", False) and len(children) > 0), - "children": children, - } - if is_root: - decoded["isRoot"] = True - return decoded - - -def decode_folder_tree_data(data: dict[str, list[CompactTreeNode]] | None) -> dict[str, list[dict[str, object]]]: - return {repo: [decode_tree_node(node, "", True) for node in nodes] - for repo, nodes in (data or {}).items()} - - -def decode_browser_entry(entry: CompactBrowserEntry, current_path: str = "") -> dict[str, object]: - return { - "folders": [ - { - "name": item.get("n", ""), - "path": f"{current_path}/{item.get('n', '')}" if current_path else item.get("n", ""), - "count": item.get("c", 0), - } - for item in entry.get("d", []) - ], - "files": [ - { - "name": item.get("n", ""), - "ext": item.get("e", ""), - "hasTxt": item.get("t", False), - "size": item.get("s", ""), - } - for item in entry.get("f", []) - ], - "current_path": current_path, - } - - -def decode_folder_browser_data(data: dict[str, dict[str, CompactBrowserEntry]] | None) -> dict[str, dict[str, dict[str, object]]]: - return {repo: {path: decode_browser_entry(entry, path) for path, entry in (browser or {}).items()} - for repo, browser in (data or {}).items()} +"""Compatibility import for backend.search.corpus.domain.formats.""" +import sys +from backend.search.corpus.domain import formats as _implementation +from backend.search.corpus.domain.formats import ( + CompactBrowserEntry as CompactBrowserEntry, + CompactCorpus as CompactCorpus, + CompactFile as CompactFile, + CompactFolder as CompactFolder, + CompactTreeNode as CompactTreeNode, + decode_browser_entry as decode_browser_entry, + decode_folder_browser_data as decode_folder_browser_data, + decode_folder_tree_data as decode_folder_tree_data, + decode_search_payload as decode_search_payload, + decode_tree_node as decode_tree_node, +) + +sys.modules[__name__] = _implementation diff --git a/backend/download/application/__init__.py b/backend/download/application/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..134f8808fe26a33906890bf48bd0f6466ea79329 --- /dev/null +++ b/backend/download/application/__init__.py @@ -0,0 +1 @@ +"""download application package.""" diff --git a/backend/download/application/warming.py b/backend/download/application/warming.py new file mode 100644 index 0000000000000000000000000000000000000000..f5e573a9885f99db3ba95125aca36dbab2238439 --- /dev/null +++ b/backend/download/application/warming.py @@ -0,0 +1,42 @@ +"""Bounded, owned speculative connection warmup for the download pool.""" +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Coroutine +from typing import Any +from fastapi import FastAPI +import aiohttp + + +async def warm_download_connection(app: FastAPI): + # Use the download pool, but never queue speculative work behind real transfers. + semaphore = app.state.upstream_semaphore + if semaphore.locked(): + return + try: + async with semaphore: + async with app.state.http_session.head( + "https://huggingface.co/robots.txt", + allow_redirects=False, + timeout=aiohttp.ClientTimeout(total=4, connect=3, sock_read=3), + ): + pass + except (aiohttp.ClientError, asyncio.TimeoutError): + # A failed warmup must not affect ping or the later download attempt. + pass + + +def schedule_download_connection_warm(app: FastAPI, *, now: Callable[[], float], + interval: Callable[[], int], + warm: Callable[[FastAPI], Coroutine[Any, Any, None]]) -> None: + state = app.state + if not getattr(state, "download_warm_enabled", False): + return + task = state.download_warm_task + current_time = now() + if task is not None and not task.done(): + return + if current_time - state.download_warm_at < interval(): + return + state.download_warm_at = current_time + state.download_warm_task = asyncio.create_task(warm(app)) diff --git a/backend/download/http/routes.py b/backend/download/http/routes.py index 8cc292501ab2ab74a1a5259bf9bd575ef1551792..5c9e6e06344889b377496a9541caaa0f593dc427 100644 --- a/backend/download/http/routes.py +++ b/backend/download/http/routes.py @@ -10,7 +10,7 @@ import aiohttp from fastapi import Request from fastapi.responses import JSONResponse, Response -from backend.proxy_streams import OwnedStreamingResponse, UpstreamLease +from backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLease class DownloadState(Protocol): diff --git a/backend/download_warm.py b/backend/download_warm.py index f5e573a9885f99db3ba95125aca36dbab2238439..4e8099924aeae93ae42c3d19b82d440f8b4608c8 100644 --- a/backend/download_warm.py +++ b/backend/download_warm.py @@ -1,42 +1,9 @@ -"""Bounded, owned speculative connection warmup for the download pool.""" -from __future__ import annotations - -import asyncio -from collections.abc import Callable, Coroutine -from typing import Any -from fastapi import FastAPI -import aiohttp - - -async def warm_download_connection(app: FastAPI): - # Use the download pool, but never queue speculative work behind real transfers. - semaphore = app.state.upstream_semaphore - if semaphore.locked(): - return - try: - async with semaphore: - async with app.state.http_session.head( - "https://huggingface.co/robots.txt", - allow_redirects=False, - timeout=aiohttp.ClientTimeout(total=4, connect=3, sock_read=3), - ): - pass - except (aiohttp.ClientError, asyncio.TimeoutError): - # A failed warmup must not affect ping or the later download attempt. - pass - - -def schedule_download_connection_warm(app: FastAPI, *, now: Callable[[], float], - interval: Callable[[], int], - warm: Callable[[FastAPI], Coroutine[Any, Any, None]]) -> None: - state = app.state - if not getattr(state, "download_warm_enabled", False): - return - task = state.download_warm_task - current_time = now() - if task is not None and not task.done(): - return - if current_time - state.download_warm_at < interval(): - return - state.download_warm_at = current_time - state.download_warm_task = asyncio.create_task(warm(app)) +"""Compatibility import for backend.download.application.warming.""" +import sys +from backend.download.application import warming as _implementation +from backend.download.application.warming import ( + schedule_download_connection_warm as schedule_download_connection_warm, + warm_download_connection as warm_download_connection, +) + +sys.modules[__name__] = _implementation diff --git a/backend/folder_contents.py b/backend/folder_contents.py index c205ffbcc2b8ae60f9c245a5a21c4c5e9335f243..d7f072c10746db8f5d27decf0801cda3936a5ad9 100644 --- a/backend/folder_contents.py +++ b/backend/folder_contents.py @@ -1,84 +1,12 @@ -"""Directory browser lookup against a caller-owned search index snapshot.""" -from __future__ import annotations - -from collections.abc import Callable, Mapping, Sequence -from typing import cast - -SearchRecord = dict[str, object] -BrowserEntries = Mapping[str, Mapping[str, SearchRecord]] -FolderIndex = Mapping[str, Mapping[str, Sequence[int]]] -RepoIndices = Mapping[str, Sequence[int]] - - -def get_folder_contents(repo: str, path: str, *, - get_browser: Callable[[], BrowserEntries], - get_folder_index: Callable[[], FolderIndex], - get_repo_indices: Callable[[], RepoIndices], - get_records: Callable[[], Sequence[SearchRecord]], - enrich_browser_entry: Callable[[str, str, SearchRecord], SearchRecord], - build_record_link: Callable[[SearchRecord], str], - build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord: - """Prefer precomputed entries, otherwise count and project the indexed subtree.""" - if repo in get_browser(): - repo_browser = get_browser().get(repo, {}) or {} - if path in repo_browser: - return enrich_browser_entry(repo, path, repo_browser[path]) - if path == "" and "" in repo_browser: - return enrich_browser_entry(repo, path, repo_browser[""]) - return _from_index(repo, path, get_folder_index, get_repo_indices, get_records, - build_record_link, build_record_path_url) - - -def _from_index(repo: str, path: str, get_folder_index: Callable[[], FolderIndex], - get_repo_indices: Callable[[], RepoIndices], get_records: Callable[[], Sequence[SearchRecord]], - build_record_link: Callable[[SearchRecord], str], - build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord: - path_parts = [p for p in path.strip("/").split("/") if p] - path_depth = len(path_parts) - repo_folders = get_folder_index().get(repo) - candidate_indices = (repo_folders.get("/".join(path_parts), []) - if repo_folders is not None else get_repo_indices().get(repo, [])) - - def is_under(rec_folders: list[str], prefix: list[str]) -> bool: - return rec_folders[:len(prefix)] == prefix - matching = [get_records()[i] for i in candidate_indices - if is_under(cast(list[str], get_records()[i].get("Folder", []) or []), path_parts)] - result_folders = _subfolder_results(matching, path_parts, path_depth) - direct_files = _direct_file_results(matching, path_depth, build_record_link, build_record_path_url) - return {"folders": result_folders, "files": direct_files, "current_path": path} - - -def _subfolder_results(matching: Sequence[SearchRecord], path_parts: list[str], - path_depth: int) -> list[SearchRecord]: - subfolder_names: set[str] = set() - subfolder_counts: dict[str, int] = {} - for rec in matching: - folders = cast(list[str], rec.get("Folder", []) or []) - if len(folders) > path_depth: - name = folders[path_depth] - subfolder_names.add(name) - subfolder_counts[name] = subfolder_counts.get(name, 0) + 1 - result_folders: list[SearchRecord] = [] - for fname in sorted(subfolder_names): - full_path = "/".join(path_parts + [fname]) if path_parts else fname - result_folders.append({"name": fname, "path": full_path, "count": subfolder_counts.get(fname, 0)}) - return result_folders - - -def _direct_file_results(matching: Sequence[SearchRecord], path_depth: int, - build_record_link: Callable[[SearchRecord], str], - build_record_path_url: Callable[[SearchRecord], str]) -> list[SearchRecord]: - direct_files: list[SearchRecord] = [] - for rec in matching: - folders = cast(list[str], rec.get("Folder", []) or []) - if len(folders) == path_depth: - direct_files.append({ - "name": rec.get("File", ""), - "ext": rec.get("Extension", ""), - "link": rec.get("Link") or build_record_link(rec), - "path": rec.get("Path") or build_record_path_url(rec), - "hasTxt": rec.get("HasTxt", False), - "size": rec.get("Size", ""), - }) - direct_files.sort(key=lambda f: cast(str, f["name"])) - return direct_files +"""Compatibility import for backend.search.corpus.domain.folder_contents.""" +import sys +from backend.search.corpus.domain import folder_contents as _implementation +from backend.search.corpus.domain.folder_contents import ( + BrowserEntries as BrowserEntries, + FolderIndex as FolderIndex, + RepoIndices as RepoIndices, + SearchRecord as SearchRecord, + get_folder_contents as get_folder_contents, +) + +sys.modules[__name__] = _implementation diff --git a/backend/folder_tree.py b/backend/folder_tree.py index f8457211ed6268010b79b302313d7cfb37e10897..7fd88dbe7fe444f354f7cbb9d653e33c9ad1a703 100644 --- a/backend/folder_tree.py +++ b/backend/folder_tree.py @@ -1,69 +1,9 @@ -"""Build search filter trees from a caller-owned index snapshot.""" -from __future__ import annotations - -from collections.abc import Mapping, Sequence -from typing import NotRequired, TypedDict, cast - - -class FolderTreeNode(TypedDict): - name: str - path: str - children: list[FolderTreeNode] - count: int - hasDirectFiles: bool - hasChildren: bool - showSelfToggle: bool - isRoot: NotRequired[bool] - - -def build_folder_tree(repo: str, folder_index: Mapping[str, Mapping[str, Sequence[int]]], - repo_records_map: Mapping[str, Sequence[int]], - records: Sequence[dict[str, object]]) -> list[FolderTreeNode]: - """Preserve corpus counts, stable child order and direct-file toggles.""" - if repo not in folder_index: - return [] - repo_name_short = repo.split("/")[-1] - tree_root: FolderTreeNode = { - "name": repo_name_short, - "path": "", - "children": [], - "count": 0, - "hasDirectFiles": False, - "hasChildren": False, - "showSelfToggle": False, - "isRoot": True, - } - node_map: dict[str, FolderTreeNode] = {"": tree_root} - for path, idx_list in folder_index[repo].items(): - if path == "": - tree_root["count"] = len(idx_list) - continue - parts = path.split("/") - for depth in range(1, len(parts) + 1): - key = "/".join(parts[:depth]) - if key not in node_map: - parent_key = "/".join(parts[:depth - 1]) if depth > 1 else "" - parent = node_map[parent_key] - node: FolderTreeNode = { - "name": parts[depth - 1], - "path": key, - "children": [], - "count": 0, - "hasDirectFiles": False, - "hasChildren": False, - "showSelfToggle": False, - } - node_map[key] = node - parent["children"].append(node) - node_map[path]["count"] = len(idx_list) - direct_file_dirs: set[str] = set() - for idx in repo_records_map.get(repo, []): - rec = records[idx] - folders = cast(list[str], rec.get("Folder", []) or []) - direct_file_dirs.add("/".join(folders)) - for path_key, node in node_map.items(): - node["hasDirectFiles"] = path_key in direct_file_dirs - node["children"].sort(key=lambda child: child["name"]) - node["hasChildren"] = len(node["children"]) > 0 - node["showSelfToggle"] = bool(path_key and node["hasDirectFiles"] and node["hasChildren"]) - return [tree_root] +"""Compatibility import for backend.search.corpus.domain.folder_tree.""" +import sys +from backend.search.corpus.domain import folder_tree as _implementation +from backend.search.corpus.domain.folder_tree import ( + FolderTreeNode as FolderTreeNode, + build_folder_tree as build_folder_tree, +) + +sys.modules[__name__] = _implementation diff --git a/backend/proxy_streams.py b/backend/proxy_streams.py index b27894a68f384de9f3463f8096d591cf754ed313..6497818cfe21e1b1a26a043ad882148b3e12d330 100644 --- a/backend/proxy_streams.py +++ b/backend/proxy_streams.py @@ -1,287 +1,11 @@ -"""Own upstream responses across the route-to-ASGI streaming handoff.""" -import asyncio -import inspect -from collections.abc import AsyncIterator, Awaitable, Callable, Mapping -from types import TracebackType -import aiohttp -from fastapi.responses import StreamingResponse -from starlette.background import BackgroundTask -from starlette.responses import ContentStream, Response -from starlette.types import Receive, Scope, Send - - -class OwnedStreamingResponse(StreamingResponse): - def __init__(self, content: ContentStream, *, cleanup: Callable[[], Awaitable[None] | None], - status_code: int = 200, headers: Mapping[str, str] | None = None, - media_type: str | None = None, background: BackgroundTask | None = None) -> None: - super().__init__(content, status_code=status_code, headers=headers, media_type=media_type, background=background) - self.cleanup = cleanup - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - try: - await super().__call__(scope, receive, send) - finally: - # A disconnect may happen before the generator's first iteration. - try: - result = self.cleanup() - if inspect.isawaitable(result): - await result - finally: - close = getattr(self.body_iterator, "aclose", None) - if close is not None: - await close() - - -class UpstreamLease: - """Own an upstream response and an optional, already-acquired pool slot.""" - - def __init__(self, semaphore: asyncio.Semaphore | None = None) -> None: - self.response: aiohttp.ClientResponse | None = None - self.semaphore = semaphore - self.closed = False - self.transferred = False - - def close(self) -> None: - if self.closed: - return - try: - if self.response is not None: - self.response.release() - self.response = None - self.closed = True - finally: - if self.semaphore is not None: - self.semaphore.release() - self.semaphore = None - - def __enter__(self) -> "UpstreamLease": - return self - - def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, - traceback: TracebackType | None) -> None: - if not self.transferred: - self.close() - - async def chunks(self, error_label: str) -> AsyncIterator[bytes]: - try: - response = self.response - if response is None: - raise RuntimeError("upstream response unavailable") - async for chunk in response.content.iter_chunked(65536): - yield chunk - except Exception as exc: - print(f"{error_label}: {exc}") - raise - finally: - self.close() - - def streaming_response(self, content: ContentStream, *, status_code: int = 200, - headers: Mapping[str, str] | None = None, media_type: str | None = None, - background: BackgroundTask | None = None) -> OwnedStreamingResponse: - response = OwnedStreamingResponse(content, cleanup=self.close, status_code=status_code, - headers=headers, media_type=media_type, background=background) - self.transferred = True - return response - - -class SharedRangeFlight: - """Stream one bounded response to independently owned subscribers.""" - - def __init__(self, create: Callable[[], Awaitable[Response]], limit: int, - finished: Callable[["SharedRangeFlight"], None]) -> None: - self.create = create - self.limit = limit - self.finished = finished - self.ready: asyncio.Future[bool] = asyncio.get_running_loop().create_future() - self.ready.add_done_callback(lambda future: None if future.cancelled() else future.exception()) - self.changed = asyncio.Event() - self.started = asyncio.Event() - self.task: asyncio.Task[None] | None = None - self.response: Response | None = None - self.headers: dict[str, str] = {} - self.chunks: list[bytes | memoryview] = [] - self.size = 0 - self.subscribers = 0 - self.shared = False - self.done = False - self.error: BaseException | None = None - self.close_error: BaseException | None = None - self._response_cleaned = False - self._iterator_closed = False - - def subscribe(self) -> "RangeSubscription": - self.subscribers += 1 - if self.task is None: - self.task = asyncio.create_task(self._run()) - self.task.add_done_callback(self._settled) - return RangeSubscription(self) - - def _settled(self, task: asyncio.Task[None]) -> None: - error = asyncio.CancelledError() if task.cancelled() else task.exception() - if error is not None and self.error is None: - self.error = error - if not self.done: - self.done = True - if not self.ready.done(): - self.ready.set_exception(self.error or RuntimeError("range flight stopped")) - self.changed.set() - if not self.subscribers: - self.finished(self) - - async def _release_response(self) -> None: - response = self.response - if response is None: - return - errors: list[BaseException] = [] - cleanup = getattr(response, "cleanup", None) - try: - if not self._response_cleaned: - if cleanup: - result = cleanup() - if inspect.isawaitable(result): - await result - self._response_cleaned = True - except BaseException as exc: - errors.append(exc) - iterator = getattr(response, "body_iterator", None) - try: - if not self._iterator_closed: - if iterator is not None: - await iterator.aclose() - self._iterator_closed = True - except BaseException as exc: - errors.append(exc) - self.close_error = (errors[0] if len(errors) == 1 else - BaseExceptionGroup("Reader range response close failures", errors) if errors else None) - if self.close_error is not None: - raise self.close_error - self.response = None - - async def _run(self) -> None: - try: - self.response = await self.create() - try: - length = int(self.response.headers.get("content-length", "")) - except (TypeError, ValueError): - length = -1 - if self.response.status_code != 206 or not 0 <= length <= self.limit: - self.ready.set_result(False) - return - self.shared = True - self.headers = dict(self.response.headers) - self.ready.set_result(True) - # A transport may suppress cancellation and still return headers. - # If all waiters left, no one can start this producer; release it. - if not self.subscribers: - return - await self.started.wait() - iterator = getattr(self.response, "body_iterator", None) - if iterator is None: - body = self.response.body - if len(body) > length: - raise ValueError("shared range body exceeds declared length") - self.chunks.append(body) - self.size = len(body) - self.changed.set() - else: - async for chunk in iterator: - if self.size + len(chunk) > length: - raise ValueError("shared range body exceeds declared length") - self.chunks.append(chunk) - self.size += len(chunk) - self.changed.set() - if self.size < length: - raise ValueError("shared range body shorter than declared length") - except BaseException as error: - self.error = error - if not self.ready.done(): - self.ready.set_exception(error) - finally: - try: - if self.shared or self.error or not self.subscribers: - await self._release_response() - finally: - self.done = True - self.changed.set() - if not self.subscribers: - self.finished(self) - - def take_response(self) -> Response | None: - response, self.response = self.response, None - return response - - def unsubscribe(self) -> None: - self.subscribers -= 1 - if self.subscribers: - return - if not self.done: - if self.task is not None: - self.task.cancel() - self.finished(self) - elif self.response is not None: - # An unclaimed declined response still owns its upstream lease. - self.task = asyncio.create_task(self._close_declined()) - self.task.add_done_callback(self._settled) - else: - self.finished(self) - - async def _close_declined(self) -> None: - try: - await self._release_response() - finally: - self.finished(self) - - async def close(self) -> None: - previous_error = self.close_error - if self.task and not self.task.done(): - self.task.cancel() - if self.task: - await asyncio.gather(self.task, return_exceptions=True) - if self.close_error is not None and self.close_error is not previous_error: - raise self.close_error - await self._release_response() - self.finished(self) - - -class RangeSubscription: - def __init__(self, flight: SharedRangeFlight) -> None: - self.flight: SharedRangeFlight | None = flight - self.closed = False - - def close(self) -> None: - if not self.closed: - self.closed = True - if self.flight is not None: - self.flight.unsubscribe() - - async def release(self) -> None: - flight = self.flight - if flight is None: - return - self.close() - if not flight.subscribers and flight.task: - await asyncio.gather(flight.task, return_exceptions=True) - self.flight = None - - async def stream(self) -> AsyncIterator[bytes | memoryview]: - cursor = 0 - flight = self.flight - if flight is None: - return - flight.started.set() - try: - while not self.closed: - while cursor < len(flight.chunks): - chunk = flight.chunks[cursor] - cursor += 1 - yield chunk - if flight.done: - if flight.error: - raise flight.error - return - flight.changed.clear() - if cursor < len(flight.chunks) or flight.done: - continue - await flight.changed.wait() - finally: - await self.release() +"""Compatibility import for backend.shared.transport.streams.""" +import sys +from backend.shared.transport import streams as _implementation +from backend.shared.transport.streams import ( + OwnedStreamingResponse as OwnedStreamingResponse, + RangeSubscription as RangeSubscription, + SharedRangeFlight as SharedRangeFlight, + UpstreamLease as UpstreamLease, +) + +sys.modules[__name__] = _implementation diff --git a/backend/reader/archive/domain/content.py b/backend/reader/archive/domain/content.py index 8b6d05ef71a1b7ff6e31a53d5c41014d2323415f..fc6611cfe3c3ff8c8ded0c76d7a46270ce034a67 100644 --- a/backend/reader/archive/domain/content.py +++ b/backend/reader/archive/domain/content.py @@ -6,7 +6,7 @@ from urllib.parse import unquote, urlparse import zipfile import zlib -from backend.reader_archive import ( +from backend.reader.archive.domain.validation import ( ReaderArchiveInvalidError as ReaderArchiveInvalidError, ReaderArchiveLimitError as ReaderArchiveLimitError, ReaderArchiveLimits as ReaderArchiveLimits, diff --git a/backend/reader/archive/domain/validation.py b/backend/reader/archive/domain/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..f40f429355ad60be330568ef90b7ec312fde678c --- /dev/null +++ b/backend/reader/archive/domain/validation.py @@ -0,0 +1,156 @@ +"""Bounded ZIP validation for reader archives with caller-owned limits.""" +from __future__ import annotations + +import io +import re +import zipfile +from typing import Protocol, cast + + +class ReaderArchiveLimits(Protocol): + """Limits are read on every use so callers may replace them at any time.""" + + @property + def READER_RESOURCE_MAX_ARCHIVE_BYTES(self) -> int: ... + @property + def READER_ARCHIVE_MAX_ENTRIES(self) -> int: ... + @property + def READER_ARCHIVE_MAX_EXPANDED_BYTES(self) -> int: ... + @property + def READER_ARCHIVE_MAX_COMPRESSION_RATIO(self) -> int: ... + @property + def READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES(self) -> int: ... + @property + def READER_ARCHIVE_MAX_METADATA_BYTES(self) -> int: ... + @property + def READER_ARCHIVE_MEMBER_RE(self) -> re.Pattern[str]: ... + + +class ReaderArchiveLimitError(ValueError): + pass + + +class ReaderArchiveInvalidError(ValueError): + pass + + +class ReaderDocumentLimitError(ValueError): + pass + + +def _plain_int(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +def _is_bytes(value: object) -> bool: + return isinstance(value, bytes) + + +def _is_str(value: object) -> bool: + return isinstance(value, str) + + +def validate_reader_archive(archive: bytes, limits: ReaderArchiveLimits) -> None: + if len(archive) > limits.READER_RESOURCE_MAX_ARCHIVE_BYTES: + raise ReaderArchiveLimitError("阅读文件过大") + try: + # Use the stdlib's EOCD/ZIP64 parser before ZipFile allocates its directory. + # These bounded EOCD fields are stdlib internals missing from typeshed. + zip_internal = cast(object, zipfile) + end_record = getattr(zip_internal, "_EndRecData")(io.BytesIO(archive)) + if not end_record: + raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") + central_directory_size = end_record[getattr(zip_internal, "_ECD_SIZE")] + directory_offset = end_record[getattr(zip_internal, "_ECD_OFFSET")] + entry_count = end_record[getattr(zip_internal, "_ECD_ENTRIES_TOTAL")] + if (end_record[getattr(zip_internal, "_ECD_DISK_NUMBER")] != 0 + or end_record[getattr(zip_internal, "_ECD_DISK_START")] != 0 + or end_record[getattr(zip_internal, "_ECD_ENTRIES_THIS_DISK")] != entry_count + or len(end_record[getattr(zip_internal, "_ECD_COMMENT")]) != end_record[getattr(zip_internal, "_ECD_COMMENT_SIZE")] + or (end_record[getattr(zip_internal, "_ECD_SIGNATURE")] != getattr(zip_internal, "stringEndArchive64") + and (central_directory_size == 0xffffffff or directory_offset == 0xffffffff))): + raise ReaderArchiveInvalidError("阅读文件元数据无效") + if central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES: + raise ReaderArchiveLimitError("阅读文件元数据过大") + if entry_count > limits.READER_ARCHIVE_MAX_ENTRIES: + raise ReaderArchiveLimitError("阅读文件条目过多") + if directory_offset + central_directory_size > len(archive): + raise ReaderArchiveInvalidError("阅读文件元数据无效") + with zipfile.ZipFile(io.BytesIO(archive)) as book_zip: + infos = book_zip.infolist() + if len(infos) > limits.READER_ARCHIVE_MAX_ENTRIES: + raise ReaderArchiveLimitError("阅读文件条目过多") + + if len(infos) != entry_count: + raise ReaderArchiveInvalidError("阅读文件条目数无效") + central_directory_offset = book_zip.start_dir + archive_comment = book_zip.comment + if ( + not _plain_int(central_directory_size) + or central_directory_size < 0 + or central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES + or not _plain_int(central_directory_offset) + or central_directory_offset < 0 + or central_directory_offset > len(archive) + or central_directory_size > len(archive) - central_directory_offset + or not _is_bytes(archive_comment) + ): + raise ReaderArchiveInvalidError("阅读文件元数据无效") + + expanded = 0 + compressed = 0 + metadata_bytes = len(archive_comment) + for info in infos: + filename = info.orig_filename + extra = info.extra + comment = info.comment + if not _is_str(filename) or not _is_bytes(extra) or not _is_bytes(comment): + raise ReaderArchiveInvalidError("阅读文件元数据无效") + name = filename.replace("\\", "/") + name_parts = name.split("/") + if (not name or name.startswith("/") or "\x00" in name + or any(part in {".", ".."} for part in name_parts) + or any(not part for part in name_parts[:-1]) + or not limits.READER_ARCHIVE_MEMBER_RE.fullmatch(name)): + raise ReaderArchiveInvalidError("阅读文件包含不安全路径") + try: + filename_bytes = len(filename.encode("utf-8", "surrogatepass")) + except (UnicodeError, AttributeError) as exc: + raise ReaderArchiveInvalidError("阅读文件元数据无效") from exc + metadata_bytes += 46 + filename_bytes + len(extra) + len(comment) + if metadata_bytes > limits.READER_ARCHIVE_MAX_METADATA_BYTES: + raise ReaderArchiveLimitError("阅读文件元数据过大") + + file_size = info.file_size + compressed_size = info.compress_size + header_offset = info.header_offset + if ( + not _plain_int(file_size) + or file_size < 0 + or not _plain_int(compressed_size) + or compressed_size < 0 + or compressed_size > len(archive) + or not _plain_int(header_offset) + or header_offset < 0 + or header_offset >= len(archive) + or header_offset >= central_directory_offset + ): + raise ReaderArchiveInvalidError("阅读文件条目无效") + expanded += file_size + compressed += compressed_size + if expanded > limits.READER_ARCHIVE_MAX_EXPANDED_BYTES: + raise ReaderArchiveLimitError("阅读文件展开后过大") + if file_size and (compressed_size == 0 or file_size > compressed_size * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO): + raise ReaderArchiveLimitError("阅读文件压缩比过高") + + if compressed == 0: + if expanded: + raise ReaderArchiveLimitError("阅读文件压缩比过高") + elif expanded > compressed * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO: + raise ReaderArchiveLimitError("阅读文件压缩比过高") + if compressed > len(archive): + raise ReaderArchiveInvalidError("阅读文件条目无效") + except (ReaderArchiveLimitError, ReaderArchiveInvalidError): + raise + except Exception as exc: + raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") from exc diff --git a/backend/reader/catalog/application/indexes.py b/backend/reader/catalog/application/indexes.py index c850e588469b93db709036a734cc934881b4b0f7..2af92616a2bb974bff62378cfe751e4239848769 100644 --- a/backend/reader/catalog/application/indexes.py +++ b/backend/reader/catalog/application/indexes.py @@ -7,8 +7,8 @@ from contextlib import AbstractContextManager from dataclasses import dataclass from typing import Protocol -from backend.reader_index import ReaderIndexBuild -from backend.search_execution import SearchBusy, SearchExecutor +from backend.reader.catalog.domain.index import ReaderIndexBuild +from backend.search.infrastructure.executor import SearchBusy, SearchExecutor Record = dict[str, object] diff --git a/backend/reader/catalog/domain/__init__.py b/backend/reader/catalog/domain/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..712f2f6bc9e8054992675d8071acf13b1f9aa81b --- /dev/null +++ b/backend/reader/catalog/domain/__init__.py @@ -0,0 +1 @@ +"""reader catalog domain package.""" diff --git a/backend/reader/catalog/domain/assets.py b/backend/reader/catalog/domain/assets.py new file mode 100644 index 0000000000000000000000000000000000000000..590af54c31d91a462cc61962a43db4d4bd12d53c --- /dev/null +++ b/backend/reader/catalog/domain/assets.py @@ -0,0 +1,154 @@ +"""Pure validation and decoding for the Reader-Assets sidecar.""" + +import gzip +import io +import json +import posixpath +import re +from typing import cast + +from backend.shared.transport.upstream import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/tests + + +READER_ASSET_FILENAMES = { + "p": {"document.pdf", "linearized.pdf", "page-manifest.json"}, + "e": {"document.epub", "book.epub", "document.mobi", "document.azw", "document.azw3", "document.fb2", "chapter-manifest.json"}, + "d": {"document.docx"}, + "h": {"document.html"}, + "t": {"document.txt", "document.vcf", "document.ini"}, + "k": {"document.md"}, + "i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp", "page-manifest.json"}, + "a": {"audio.mp3", "audio.wav", "audio.m4a", "audio.flac", "audio.mpga"}, + "v": {"video.mp4", "video.mov"}, + "f": {"document.swf"}, +} +READER_BUCKET_PATH_RE = re.compile( + r"^(?:documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:document\.(?:txt|md|html|docx|pdf|vcf|ini))|" + r"chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\.json|epub-search-index\.json\.gz|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*)|" + r"media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\.[a-z0-9]+|video\.[a-z0-9]+|document\.swf)|" + r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/(?:document\.webp|page-manifest\.json|pages/page-[0-9]{6}\.webp)|" + r"native/ebook/chm/[0-9a-f]{64}/document\.epub|" + r"derived/[a-zA-Z0-9._-]+/[a-z0-9]{32}/(?:document\.pdf|page-manifest\.json|pages/page-[0-9]{6}\.webp|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|" + r"objects/(?P[0-9a-f]{2})/(?P=djvu_prefix)[0-9a-f]{62}/[0-9a-f]{16}/document\.djvu|" + r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))|" + r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl|png)|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|document\.pdf))$" +) +READER_EBOOK_BUCKET = "vomebook/reader-assets-v2" +READER_ALLOWED_BUCKETS = {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"} + + +def decode_reader_assets( + raw: bytes, + max_compressed_bytes: int = 5 * 1024 * 1024, + max_decompressed_bytes: int = 50 * 1024 * 1024, +) -> dict[str, object]: + if len(raw) > max_compressed_bytes: + raise ValueError("reader assets sidecar is too large") + with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: + decoded = stream.read(max_decompressed_bytes + 1) + if len(decoded) > max_decompressed_bytes: + raise ValueError("reader assets sidecar expands beyond limit") + payload: object = json.loads(decoded) + payload_map = cast(dict[str, object], payload) if isinstance(payload, dict) else None + files = payload_map.get("f") if payload_map is not None and payload_map.get("v") == 1 else None + if not isinstance(files, dict): + raise ValueError("invalid reader assets sidecar") + file_map = cast(dict[object, object], files) + clean: dict[str, dict[str, object]] = {} + for key, raw_entry in file_map.items(): + if not isinstance(key, str) or not isinstance(raw_entry, dict): + continue + entry = cast(dict[str, object], raw_entry) + if entry.get("s") not in (2, 3, 4): + continue + if entry.get("s") == 2: + path = entry.get("p") + mode = entry.get("m") + if not isinstance(path, str) or not isinstance(mode, str) or mode not in READER_ASSET_FILENAMES: + continue + if entry.get("b") not in READER_ALLOWED_BUCKETS: + continue + path_pattern = READER_BUCKET_PATH_RE + image_page_path = bool(re.fullmatch(r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp)/[0-9a-f]{64}/pages/page-[0-9]{6}\.webp", path)) + valid_filename = (posixpath.basename(path) in READER_ASSET_FILENAMES[mode] + or (mode == "i" and image_page_path) + or (mode == "p" and entry.get("b") == "vomebook/pdf-pages-v2" + and path.endswith("/reading-manifest.json"))) + if ( + not path_pattern.fullmatch(path) + or not valid_filename + ): + continue + chapter_manifest = entry.get("c") + fallback = entry.get("f") + ocr_manifest = entry.get("o") + chapter_bucket = entry.get("cb") + bucket = entry.get("b") + document_path, document_bucket = entry.get("pd"), entry.get("pdb") + if (document_path is not None or document_bucket is not None) and ( + mode != "p" or not path.endswith("/page-manifest.json") + or not isinstance(document_bucket, str) + or document_bucket not in READER_ALLOWED_BUCKETS + or not isinstance(document_path, str) + or not READER_BUCKET_PATH_RE.fullmatch(document_path) + or not document_path.endswith("/document.pdf") + ): + continue + if chapter_manifest is not None and ( + mode not in {"e", "p"} + or not isinstance(chapter_manifest, str) + or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest) + or not chapter_manifest.endswith("/chapter-manifest.json") + ): + continue + if chapter_manifest is not None and chapter_bucket is None: + continue + if chapter_bucket is not None and ( + chapter_bucket != READER_EBOOK_BUCKET or not isinstance(chapter_manifest, str) + or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest) + or not (chapter_manifest.startswith("ebook-chapters/") + or (chapter_bucket == "vomebook/reader-assets-v2" + and chapter_manifest.startswith("chapters/ebook/"))) + ): + continue + fallback_is_chm = (bucket == READER_EBOOK_BUCKET and isinstance(fallback, str) + and READER_BUCKET_PATH_RE.fullmatch(fallback) + and fallback.endswith("/document.epub")) + if fallback is not None and not fallback_is_chm: + continue + if ocr_manifest is not None and ( + not isinstance(ocr_manifest, str) + or not READER_BUCKET_PATH_RE.fullmatch(ocr_manifest) + or not ocr_manifest.endswith("/ocr-manifest.json") + ): + continue + if entry.get("b") is not None and entry.get("b") not in READER_ALLOWED_BUCKETS: + continue + if entry.get("ob") is not None and entry.get("ob") != "vomebook/pdf-pages-v2": + continue + if bucket == "vomebook/pdf-pages-v2": + if mode == "p" and (not path.endswith(("/page-manifest.json", "/reading-manifest.json", "/document.pdf")) + or not READER_BUCKET_PATH_RE.fullmatch(path)): + continue + clean[key] = { + "s": 2, + "m": mode, + "p": path, + **({"b": bucket} if bucket else {}), + **({"pd": document_path, "pdb": document_bucket} if document_path else {}), + **({"c": chapter_manifest} if chapter_manifest else {}), + **({"cb": chapter_bucket} if chapter_bucket else {}), + **({"f": fallback} if fallback else {}), + **({"o": ocr_manifest} if ocr_manifest else {}), + **({"ob": "vomebook/pdf-pages-v2"} if entry.get("ob") else {}), + **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {}), + } + else: + ocr_manifest = entry.get("o") + if (isinstance(ocr_manifest, str) and READER_BUCKET_PATH_RE.fullmatch(ocr_manifest) + and ocr_manifest.endswith("/ocr-manifest.json")): + clean[key] = {"s": 3, "m": "p", "o": ocr_manifest, "b": "vomebook/pdf-pages-v2", + **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {})} + else: + clean[key] = {"s": 4} + return {"v": 1, "f": clean} diff --git a/backend/reader/catalog/domain/index.py b/backend/reader/catalog/domain/index.py new file mode 100644 index 0000000000000000000000000000000000000000..381b1e45fc5425df9679e073159babdde1e1094b --- /dev/null +++ b/backend/reader/catalog/domain/index.py @@ -0,0 +1,54 @@ +"""Incremental Reader index construction without publishing partial results.""" + +from collections.abc import Callable +from typing import TypedDict, cast + + +class ReaderIndexBuild(TypedDict): + generation: int + records: list[dict[str, object]] + next: int + indices: list[int] + repos: dict[str, list[int]] + keys: dict[str, int] + ids: dict[str, list[int]] + legacy_ids: dict[str, list[int]] + + +def new_build(generation: int, records: list[dict[str, object]]) -> ReaderIndexBuild: + return {"generation": generation, "records": records, "next": 0, + "indices": [], "repos": {}, "keys": {}, "ids": {}, "legacy_ids": {}} + + +def advance_build(build: ReaderIndexBuild, limit: int, deadline: float, *, + now: Callable[[], float], source_id: Callable[[str], str], + asset_key: Callable[[dict[str, object]], str], + record_link: Callable[[dict[str, object]], str], + dataset_url: Callable[[str, str], str], + reader_extensions: frozenset[str]) -> bool: + """Advance at most one batch; callers own generation checks and publication.""" + end = min(len(build["records"]), build["next"] + limit) + while build["next"] < end: + idx = build["next"] + rec = build["records"][idx] + repo = rec.get("Repo", "") + build["keys"][asset_key(rec)] = idx + current_url = cast(str, rec.get("Link") or record_link(rec)) + build["ids"].setdefault(source_id(current_url), []).append(idx) + # Old links omitted a repeated filename extension; index the historical + # alias without changing the canonical identity or resolving collisions. + name, ext, folders = rec.get("File", ""), rec.get("Extension", ""), rec.get("Folder", []) + if (isinstance(repo, str) and repo.startswith("VoiceOfML/") and isinstance(name, str) + and isinstance(ext, str) and ext and name.lower().endswith("." + ext.lower()) + and isinstance(folders, list) and all(isinstance(part, str) for part in cast(list[object], folders))): + legacy_path = "/".join([*cast(list[str], folders), name]) + legacy_url = dataset_url(repo, legacy_path) + if legacy_url != (rec.get("Link") or record_link(rec)): + build["legacy_ids"].setdefault(source_id(legacy_url), []).append(idx) + if rec.get("_ext_lower", "") in reader_extensions: + build["indices"].append(idx) + build["repos"].setdefault(cast(str, repo), []).append(idx) + build["next"] += 1 + if now() >= deadline: + break + return build["next"] >= len(build["records"]) diff --git a/backend/reader/catalog/infrastructure/__init__.py b/backend/reader/catalog/infrastructure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..109ed820a5c3f3137d7c8fe4fd4c4b8de5238e20 --- /dev/null +++ b/backend/reader/catalog/infrastructure/__init__.py @@ -0,0 +1 @@ +"""reader catalog infrastructure package.""" diff --git a/backend/reader/catalog/infrastructure/v3.py b/backend/reader/catalog/infrastructure/v3.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e03bd001e72c75bd27399d0d4eaffd1a86582b --- /dev/null +++ b/backend/reader/catalog/infrastructure/v3.py @@ -0,0 +1,161 @@ +"""Pinned v3 catalog projection, using only canonical bucket metadata URLs.""" +import asyncio +import hashlib +import json +import re +from typing import Callable, Literal, ParamSpec, TypeVar, cast, overload + +import aiohttp + +from backend.shared.transport.upstream import open_download_response, validate_fixed_source_redirect_url + +BUCKET = "vomebook/reader-assets-v2" +BASE = f"https://huggingface.co/buckets/{BUCKET}/resolve/" +POINTER = "reader-index/v3/current.json" +MAX_BYTES = 8 * 1024 * 1024 + + +def sha(value: object) -> re.Match[str] | bool | None: + return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value) + + +def catalog_path(generation: object) -> str: + if not sha(generation): + raise ValueError("invalid v3 catalog generation") + return f"reader-index/v3/generations/{generation}/catalog.json" + + +def decode_catalog(pointer: dict[str, object], raw: bytes) -> dict[str, object]: + from backend.reader.catalog.domain.assets import READER_BUCKET_PATH_RE + if pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer": + raise ValueError("invalid v3 pointer") + generation = pointer.get("generation") + ref = cast(dict[str, object], pointer.get("catalog", {})) + if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation) + or ref.get("role") != "runtime" or type(ref.get("bytes")) is not int + or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES or not sha(ref.get("sha256")) + or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]): + raise ValueError("v3 catalog resource mismatch") + catalog = cast(dict[str, object], json.loads(raw)) + body = {k: v for k, v in catalog.items() if k != "generation"} + digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"), + allow_nan=False).encode()).hexdigest() + if (catalog.get("version") != 3 or catalog.get("kind") != "reader-reading-catalog" + or catalog.get("generation") != generation or digest != generation + or not isinstance(catalog.get("files"), dict)): + raise ValueError("invalid v3 catalog identity") + overrides: dict[str, dict[str, object]] = {} + for key, raw_entry in cast(dict[object, object], catalog["files"]).items(): + if not isinstance(key, str) or not key or not isinstance(raw_entry, dict): + raise ValueError("invalid v3 source key") + entry = cast(dict[str, object], raw_entry) + resource = cast(dict[str, object], entry.get("resource", {})) + source = entry.get("source_sha256") + path = resource.get("path", "") + if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation")) + or resource.get("bucket") != "vomebook/pdf-pages-v2" or resource.get("role") != "runtime" + or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path) + or not path.startswith(f"objects/{source[:2]}/{source}/") + or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256")) + or type(resource.get("bytes")) is not int or cast(int, resource["bytes"]) < 1): + raise ValueError("invalid v3 reading reference") + overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]} + return {"generation": generation, "catalog_sha256": ref["sha256"], + "files": overrides, "catalog": ref, + **({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})} + + +def validate_base_ref(ref: object) -> dict[str, object]: + if not isinstance(ref, dict): + raise ValueError("invalid unified base sidecar") + ref = cast(dict[str, object], ref) + if (ref.get("bucket") != BUCKET or ref.get("role") != "runtime" + or not sha(ref.get("sha256")) or ref.get("path") != + f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz" + or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES): + raise ValueError("invalid unified base sidecar") + return ref + + +_DecodeParams = ParamSpec("_DecodeParams") +_DecodeResult = TypeVar("_DecodeResult") + + +async def decode_in_thread(func: Callable[_DecodeParams, _DecodeResult], + *args: _DecodeParams.args, **kwargs: _DecodeParams.kwargs) -> _DecodeResult: + # Keep the refresh owner alive until its worker exits even after cancellation. + # Otherwise a subsequent refresh could start another large decode while the + # abandoned worker still holds its inputs and intermediate objects. + task = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs)) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError: + continue + except Exception: + break + if not task.cancelled(): + task.exception() # Retrieve a worker failure without replacing cancellation. + raise + + +async def load_reading_catalog(session: object) -> dict[str, object] | None: + @overload + async def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ... + + @overload + async def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ... + + async def fetch(path: str, *, missing: bool = False) -> bytes | None: + source_url = BASE + path + # Validate every redirect hop against the fixed URL or signed storage; + # metadata is mutable, so its signed targets are never reused. + response = await open_download_response( + session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10), + request_headers={"Cache-Control": "no-cache"}, + url_validator=lambda url: validate_fixed_source_redirect_url(url, source_url), + cache_redirects=False, + ) + try: + if missing and response.status == 404: + return None + if response.status != 200: + raise RuntimeError(f"v3 metadata HTTP {response.status}") + raw = bytearray() + async for chunk in response.content.iter_chunked(64 * 1024): + raw.extend(chunk) + if len(raw) > MAX_BYTES: + raise ValueError("v3 metadata exceeds limit") + return bytes(raw) + finally: + response.release() + raw = await fetch(POINTER, missing=True) + if raw is None: + return None + pointer = cast(dict[str, object], json.loads(raw)) + # Validate the exact fixed catalog path before starting another request. + path = catalog_path(pointer.get("generation")) + if cast(dict[str, object], pointer.get("catalog", {})).get("path") != path: + raise ValueError("v3 pointer path mismatch") + catalog = await fetch(path) + result = await decode_in_thread(decode_catalog, pointer, catalog) + if result.get("base_sidecar_ref"): + ref = validate_base_ref(result["base_sidecar_ref"]) + packed = await fetch(cast(str, ref["path"])) + if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]: + raise ValueError("unified base sidecar checksum mismatch") + from backend.reader.catalog.domain.assets import decode_reader_assets + result["base_sidecar"] = await decode_in_thread(decode_reader_assets, packed) + return result + + +def merge_sidecar(base: dict[str, object], catalog: dict[str, object] | None) -> dict[str, object]: + if not catalog: + return base + base = cast(dict[str, object], catalog.get("base_sidecar", base)) + return {**base, "f": {**cast(dict[str, object], base["f"]), **cast(dict[str, object], catalog["files"])}, + "v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"], + "files": len(cast(dict[str, object], catalog["files"]))}} diff --git a/backend/reader/document/application/ranges.py b/backend/reader/document/application/ranges.py index 910baa6a037882643e88b659ccac213e0b95f3ae..09311aa49773bdb62b3402f86545e135d680f52e 100644 --- a/backend/reader/document/application/ranges.py +++ b/backend/reader/document/application/ranges.py @@ -7,7 +7,7 @@ from typing import Protocol, cast from fastapi import Request from fastapi.responses import Response -from backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlight +from backend.shared.transport.streams import OwnedStreamingResponse, SharedRangeFlight from backend.reader.document.domain.policy import RangeFlightKey, RangeKey, ReaderStreamOptions diff --git a/backend/reader/document/domain/policy.py b/backend/reader/document/domain/policy.py index f0782e4847df346c4ed36d3b468a53ec9f2e00ad..c5d5bbc93aaa222594dacf6cdbebe469381177c4 100644 --- a/backend/reader/document/domain/policy.py +++ b/backend/reader/document/domain/policy.py @@ -2,7 +2,7 @@ from collections.abc import Callable, Hashable, Mapping from typing import TypedDict -from backend.reader_range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry +from backend.reader.document.domain.range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry RangeFlightKey = tuple[RangeKey, Hashable, str | None] diff --git a/backend/reader/document/domain/range_cache.py b/backend/reader/document/domain/range_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..15c1afaa1c133a89515c29988204b14e43dd1497 --- /dev/null +++ b/backend/reader/document/domain/range_cache.py @@ -0,0 +1,67 @@ +"""Safe exact-byte subrange reuse for the Reader proxy's bounded cache.""" +from __future__ import annotations + +from collections import OrderedDict +from collections.abc import Callable +from typing import Protocol +import re + +RangeKey = tuple[str, str, int | None, str | None] +RangeCacheEntry = tuple[float, bytes, dict[str, str]] + + +class RangeCacheState(Protocol): + reader_range_cache: OrderedDict[RangeKey, RangeCacheEntry] + reader_range_cache_bytes: int + + +def requested_range_bounds(header: str | None, total: int) -> tuple[int, int] | None: + """Resolve an ordinary single byte range; unknown/unsatisfiable forms return None.""" + if header is None or total <= 0: + return None + match = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", header) + if match is None: + return None + first, last = match.groups() + if not first: + if not last or int(last) == 0: + return None + return max(0, total - int(last)), total - 1 + start = int(first) + end = min(int(last), total - 1) if last else total - 1 + if start > end: + return None + return start, end + + +def cached_subrange(range_key: RangeKey, get_state: Callable[[], RangeCacheState], + get_limit: Callable[[], int], get_ttl: Callable[[], int], + now: Callable[[], float]) -> tuple[bytes, dict[str, str]] | None: + """Serve a verified contained range, evicting stale entries in LRU order.""" + requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1]) + if requested is None: + return None + start, end = (int(value) for value in requested.groups()) + if start > end or end - start + 1 > get_limit(): + return None + cache = get_state().reader_range_cache + current_time = now() + for key in reversed(list(cache)): + cached_at, payload, headers = cache[key] + if current_time - cached_at >= get_ttl(): + cache.pop(key) + get_state().reader_range_cache_bytes -= len(payload) + continue + if key[0] != range_key[0] or key[2:] != range_key[2:]: + continue + match = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", "")) + if match is None: + continue + cached_start, cached_end, total = (int(value) for value in match.groups()) + final_end = min(end, total - 1) + if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1: + cache.move_to_end(key) + body = payload[start - cached_start:final_end - cached_start + 1] + return body, {**headers, "Content-Range": f"bytes {start}-{final_end}/{total}", + "Content-Length": str(len(body))} + return None diff --git a/backend/reader/document/http/transport.py b/backend/reader/document/http/transport.py index 5fa432ec59c465c0378c71b783036c76613aa69e..4beb82c09144b5589747de8267a9f8a4797b6db3 100644 --- a/backend/reader/document/http/transport.py +++ b/backend/reader/document/http/transport.py @@ -13,8 +13,8 @@ import aiohttp from fastapi import Request from fastapi.responses import JSONResponse, Response -from backend.proxy_streams import OwnedStreamingResponse, UpstreamLease -from backend.reader_range_cache import RangeCacheState +from backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLease +from backend.reader.document.domain.range_cache import RangeCacheState from backend.reader.document.domain.policy import RangeKey, RangeCacheEntry, ReaderStreamOptions diff --git a/backend/reader/query/application/ocr.py b/backend/reader/query/application/ocr.py index 0fa22b8c21867e5b3090d59e6472f1373dd487cd..723190adefa7dc09dd10db1e3e7c580e31917789 100644 --- a/backend/reader/query/application/ocr.py +++ b/backend/reader/query/application/ocr.py @@ -5,7 +5,7 @@ from collections.abc import Awaitable, Callable from typing import Protocol, cast from urllib.parse import ParseResult, parse_qs -from backend.reader_ocr import OcrPage, OcrSearchHit +from backend.reader.query.domain.ocr import OcrPage, OcrSearchHit JsonObject = dict[str, object] OcrSearch = Callable[[list[OcrPage], str, int, int], tuple[int, list[OcrSearchHit]]] diff --git a/backend/reader/query/domain/ocr.py b/backend/reader/query/domain/ocr.py new file mode 100644 index 0000000000000000000000000000000000000000..f1e40636bf9a7d9db3d044d513b3794f181fe442 --- /dev/null +++ b/backend/reader/query/domain/ocr.py @@ -0,0 +1,165 @@ +"""Bounded PDF text-index validation and original-offset search.""" +from __future__ import annotations + +from array import array +import gzip +import io +import json +import re +from typing import NotRequired, TypedDict, cast + + +class OcrSpan(TypedDict): + start: int + end: int + box: list[int | float] + + +class OcrPage(TypedDict): + page: int + text: str + folded: str + fold_map: NotRequired[array[int] | None] + layout: dict[str, object] + spans: list[OcrSpan] + + +class OcrSearchHit(TypedDict): + page: int + start: int + length: int + snippet: str + snippet_start: int + boxes: list[list[int | float]] + + +def fold_reader_ocr_text(text: str) -> tuple[str, array[int] | None]: + """Map casefold-expanded code points back to the source text.""" + folded = text.casefold() + if len(folded) == len(text): + return folded, None + pieces: list[str] = [] + fold_map: array[int] = array('I') + for index, character in enumerate(text): + piece = character.casefold() + pieces.append(piece) + fold_map.extend([index] * len(piece)) + return "".join(pieces), fold_map + + +def parse_reader_ocr_book(raw: bytes, max_bytes: int) -> tuple[list[OcrPage], int]: + """Decode and validate one v2 book index without exceeding its byte limit.""" + with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: + decoded = stream.read(max_bytes + 1) + if len(decoded) > max_bytes: + raise ValueError("PDF OCR text index is too large") + payload: object = json.loads(decoded) + if not isinstance(payload, dict): + raise ValueError("invalid PDF OCR text index") + document = cast(dict[str, object], payload) + raw_pages = document.get("pages") + if not isinstance(raw_pages, list): + raise ValueError("invalid PDF OCR text index") + pages = cast(list[object], raw_pages) + if (len(pages) > 200000 + or document.get("version") != 2 or document.get("kind") != "pdf-book-text" + or document.get("complete") is not True + or document.get("offset_unit") != "unicode-codepoint" + or document.get("page_count") != len(pages) + or not re.fullmatch(r"[0-9a-f]{64}", str(document.get("source_sha256", "")))): + raise ValueError("invalid PDF OCR text index") + output: list[OcrPage] = [] + total_bytes = 0 + previous = 0 + for raw_page in pages: + if not isinstance(raw_page, dict): + raise ValueError("invalid PDF OCR text page") + item = cast(dict[str, object], raw_page) + number, text = item.get("page"), item.get("text") + if (not isinstance(number, int) or number < 1 or number <= previous + or not isinstance(text, str)): + raise ValueError("invalid PDF OCR text page") + total_bytes += len(text.encode("utf-8")) + if total_bytes > max_bytes: + raise ValueError("PDF OCR text index is too large") + layout, spans = item.get("layout"), item.get("text_spans") + if (not isinstance(layout, dict) or cast(dict[str, object], layout).get("offset_unit") != "unicode-codepoint" + or not isinstance(spans, list)): + raise ValueError("invalid PDF text layout mapping") + previous_span_end = 0 + for raw_span in cast(list[object], spans): + if not isinstance(raw_span, dict): + raise ValueError("invalid PDF text span") + span = cast(dict[str, object], raw_span) + start, end, box = span.get("start"), span.get("end"), span.get("box") + if (not isinstance(start, int) or not isinstance(end, int) or start < previous_span_end + or end <= start or end > len(text) or not isinstance(box, list)): + raise ValueError("invalid PDF text span") + values = cast(list[object], box) + if len(values) != 4 or any(not isinstance(value, (int, float)) or value < 0 or value > 1 + for value in values): + raise ValueError("invalid PDF text span") + previous_span_end = end + folded, fold_map = fold_reader_ocr_text(text) + if fold_map is not None: + total_bytes += len(fold_map) * fold_map.itemsize + output.append({"page": number, "text": text, "folded": folded, "fold_map": fold_map, + "layout": cast(dict[str, object], layout), "spans": cast(list[OcrSpan], spans)}) + previous = number + return output, total_bytes + + +def search_reader_ocr_pages( + pages: list[OcrPage], needle: str, page: int, page_size: int +) -> tuple[int, list[OcrSearchHit]]: + """Count all non-overlapping matches; return one page in original offsets.""" + offset = (page - 1) * page_size + end_offset = offset + page_size + folded_length = len(needle) + total = 0 + results: list[OcrSearchHit] = [] + if not folded_length: + return total, results + # Once the requested page is full, only the remaining count is needed. + # Exact built-ins keep custom string methods and unusual callers on the + # existing per-match path, including their errors and side effects. + count_safe = type(needle) is str and type(page) is int and type(page_size) is int and page_size > 0 + for item in pages: + text, folded = item["text"], item["folded"] + if "fold_map" in item: + fold_map = item["fold_map"] + elif len(folded) == len(text): + fold_map = None + else: + folded, fold_map = fold_reader_ocr_text(text) + if count_safe and len(results) == page_size and type(folded) is str: + total += folded.count(needle) + continue + start = 0 + while True: + found = folded.find(needle, start) + if found < 0: + break + match_index = total + total += 1 + if offset <= match_index < end_offset: + if fold_map is None: + original_start, original_end = found, found + folded_length + else: + original_start = fold_map[found] + original_end = fold_map[found + folded_length - 1] + 1 + snippet_start = max(0, original_start - 72) + snippet_end = min(len(text), original_end + 88) + boxes = [span["box"] for span in item["spans"] + if span["end"] > original_start and span["start"] < original_end] + results.append({ + "page": item["page"], "start": original_start, + "length": original_end - original_start, + "snippet": text[snippet_start:snippet_end], + "snippet_start": original_start - snippet_start, "boxes": boxes, + }) + if count_safe and len(results) == page_size and type(folded) is str: + total += folded.count(needle, found + folded_length) + break + start = found + folded_length + return total, results diff --git a/backend/reader_archive.py b/backend/reader_archive.py index f40f429355ad60be330568ef90b7ec312fde678c..11537a7eb6701514714372927033c441ea406e40 100644 --- a/backend/reader_archive.py +++ b/backend/reader_archive.py @@ -1,156 +1,12 @@ -"""Bounded ZIP validation for reader archives with caller-owned limits.""" -from __future__ import annotations - -import io -import re -import zipfile -from typing import Protocol, cast - - -class ReaderArchiveLimits(Protocol): - """Limits are read on every use so callers may replace them at any time.""" - - @property - def READER_RESOURCE_MAX_ARCHIVE_BYTES(self) -> int: ... - @property - def READER_ARCHIVE_MAX_ENTRIES(self) -> int: ... - @property - def READER_ARCHIVE_MAX_EXPANDED_BYTES(self) -> int: ... - @property - def READER_ARCHIVE_MAX_COMPRESSION_RATIO(self) -> int: ... - @property - def READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES(self) -> int: ... - @property - def READER_ARCHIVE_MAX_METADATA_BYTES(self) -> int: ... - @property - def READER_ARCHIVE_MEMBER_RE(self) -> re.Pattern[str]: ... - - -class ReaderArchiveLimitError(ValueError): - pass - - -class ReaderArchiveInvalidError(ValueError): - pass - - -class ReaderDocumentLimitError(ValueError): - pass - - -def _plain_int(value: object) -> bool: - return isinstance(value, int) and not isinstance(value, bool) - - -def _is_bytes(value: object) -> bool: - return isinstance(value, bytes) - - -def _is_str(value: object) -> bool: - return isinstance(value, str) - - -def validate_reader_archive(archive: bytes, limits: ReaderArchiveLimits) -> None: - if len(archive) > limits.READER_RESOURCE_MAX_ARCHIVE_BYTES: - raise ReaderArchiveLimitError("阅读文件过大") - try: - # Use the stdlib's EOCD/ZIP64 parser before ZipFile allocates its directory. - # These bounded EOCD fields are stdlib internals missing from typeshed. - zip_internal = cast(object, zipfile) - end_record = getattr(zip_internal, "_EndRecData")(io.BytesIO(archive)) - if not end_record: - raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") - central_directory_size = end_record[getattr(zip_internal, "_ECD_SIZE")] - directory_offset = end_record[getattr(zip_internal, "_ECD_OFFSET")] - entry_count = end_record[getattr(zip_internal, "_ECD_ENTRIES_TOTAL")] - if (end_record[getattr(zip_internal, "_ECD_DISK_NUMBER")] != 0 - or end_record[getattr(zip_internal, "_ECD_DISK_START")] != 0 - or end_record[getattr(zip_internal, "_ECD_ENTRIES_THIS_DISK")] != entry_count - or len(end_record[getattr(zip_internal, "_ECD_COMMENT")]) != end_record[getattr(zip_internal, "_ECD_COMMENT_SIZE")] - or (end_record[getattr(zip_internal, "_ECD_SIGNATURE")] != getattr(zip_internal, "stringEndArchive64") - and (central_directory_size == 0xffffffff or directory_offset == 0xffffffff))): - raise ReaderArchiveInvalidError("阅读文件元数据无效") - if central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES: - raise ReaderArchiveLimitError("阅读文件元数据过大") - if entry_count > limits.READER_ARCHIVE_MAX_ENTRIES: - raise ReaderArchiveLimitError("阅读文件条目过多") - if directory_offset + central_directory_size > len(archive): - raise ReaderArchiveInvalidError("阅读文件元数据无效") - with zipfile.ZipFile(io.BytesIO(archive)) as book_zip: - infos = book_zip.infolist() - if len(infos) > limits.READER_ARCHIVE_MAX_ENTRIES: - raise ReaderArchiveLimitError("阅读文件条目过多") - - if len(infos) != entry_count: - raise ReaderArchiveInvalidError("阅读文件条目数无效") - central_directory_offset = book_zip.start_dir - archive_comment = book_zip.comment - if ( - not _plain_int(central_directory_size) - or central_directory_size < 0 - or central_directory_size > limits.READER_ARCHIVE_MAX_CENTRAL_DIRECTORY_BYTES - or not _plain_int(central_directory_offset) - or central_directory_offset < 0 - or central_directory_offset > len(archive) - or central_directory_size > len(archive) - central_directory_offset - or not _is_bytes(archive_comment) - ): - raise ReaderArchiveInvalidError("阅读文件元数据无效") - - expanded = 0 - compressed = 0 - metadata_bytes = len(archive_comment) - for info in infos: - filename = info.orig_filename - extra = info.extra - comment = info.comment - if not _is_str(filename) or not _is_bytes(extra) or not _is_bytes(comment): - raise ReaderArchiveInvalidError("阅读文件元数据无效") - name = filename.replace("\\", "/") - name_parts = name.split("/") - if (not name or name.startswith("/") or "\x00" in name - or any(part in {".", ".."} for part in name_parts) - or any(not part for part in name_parts[:-1]) - or not limits.READER_ARCHIVE_MEMBER_RE.fullmatch(name)): - raise ReaderArchiveInvalidError("阅读文件包含不安全路径") - try: - filename_bytes = len(filename.encode("utf-8", "surrogatepass")) - except (UnicodeError, AttributeError) as exc: - raise ReaderArchiveInvalidError("阅读文件元数据无效") from exc - metadata_bytes += 46 + filename_bytes + len(extra) + len(comment) - if metadata_bytes > limits.READER_ARCHIVE_MAX_METADATA_BYTES: - raise ReaderArchiveLimitError("阅读文件元数据过大") - - file_size = info.file_size - compressed_size = info.compress_size - header_offset = info.header_offset - if ( - not _plain_int(file_size) - or file_size < 0 - or not _plain_int(compressed_size) - or compressed_size < 0 - or compressed_size > len(archive) - or not _plain_int(header_offset) - or header_offset < 0 - or header_offset >= len(archive) - or header_offset >= central_directory_offset - ): - raise ReaderArchiveInvalidError("阅读文件条目无效") - expanded += file_size - compressed += compressed_size - if expanded > limits.READER_ARCHIVE_MAX_EXPANDED_BYTES: - raise ReaderArchiveLimitError("阅读文件展开后过大") - if file_size and (compressed_size == 0 or file_size > compressed_size * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO): - raise ReaderArchiveLimitError("阅读文件压缩比过高") - - if compressed == 0: - if expanded: - raise ReaderArchiveLimitError("阅读文件压缩比过高") - elif expanded > compressed * limits.READER_ARCHIVE_MAX_COMPRESSION_RATIO: - raise ReaderArchiveLimitError("阅读文件压缩比过高") - if compressed > len(archive): - raise ReaderArchiveInvalidError("阅读文件条目无效") - except (ReaderArchiveLimitError, ReaderArchiveInvalidError): - raise - except Exception as exc: - raise ReaderArchiveInvalidError("阅读文件不是有效 ZIP") from exc +"""Compatibility import for backend.reader.archive.domain.validation.""" +import sys +from backend.reader.archive.domain import validation as _implementation +from backend.reader.archive.domain.validation import ( + ReaderArchiveInvalidError as ReaderArchiveInvalidError, + ReaderArchiveLimitError as ReaderArchiveLimitError, + ReaderArchiveLimits as ReaderArchiveLimits, + ReaderDocumentLimitError as ReaderDocumentLimitError, + validate_reader_archive as validate_reader_archive, +) + +sys.modules[__name__] = _implementation diff --git a/backend/reader_assets.py b/backend/reader_assets.py index 930477bbe38d9b7b19389d262c0724f901627ca9..69fc97ad1fdcbf0b4269e77eb2589201bce79e61 100644 --- a/backend/reader_assets.py +++ b/backend/reader_assets.py @@ -1,154 +1,13 @@ -"""Pure validation and decoding for the Reader-Assets sidecar.""" - -import gzip -import io -import json -import posixpath -import re -from typing import cast - -from backend.upstream_http import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/tests - - -READER_ASSET_FILENAMES = { - "p": {"document.pdf", "linearized.pdf", "page-manifest.json"}, - "e": {"document.epub", "book.epub", "document.mobi", "document.azw", "document.azw3", "document.fb2", "chapter-manifest.json"}, - "d": {"document.docx"}, - "h": {"document.html"}, - "t": {"document.txt", "document.vcf", "document.ini"}, - "k": {"document.md"}, - "i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp", "page-manifest.json"}, - "a": {"audio.mp3", "audio.wav", "audio.m4a", "audio.flac", "audio.mpga"}, - "v": {"video.mp4", "video.mov"}, - "f": {"document.swf"}, -} -READER_BUCKET_PATH_RE = re.compile( - r"^(?:documents/(?:text|web|spreadsheet|office|pdf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:document\.(?:txt|md|html|docx|pdf|vcf|ini))|" - r"chapters/ebook/(?:epub|mobi|azw3|fb2|chm)/[0-9a-f]{64}/[0-9a-f]{16}/(?:chapter-manifest\.json|epub-search-index\.json\.gz|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*)|" - r"media/(?:audio|video|swf)/[a-z0-9_-]+/[0-9a-f]{64}/(?:audio\.[a-z0-9]+|video\.[a-z0-9]+|document\.swf)|" - r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp|gif)/[0-9a-f]{64}/(?:document\.webp|page-manifest\.json|pages/page-[0-9]{6}\.webp)|" - r"native/ebook/chm/[0-9a-f]{64}/document\.epub|" - r"derived/[a-zA-Z0-9._-]+/[a-z0-9]{32}/(?:document\.pdf|page-manifest\.json|pages/page-[0-9]{6}\.webp|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|" - r"objects/(?P[0-9a-f]{2})/(?P=djvu_prefix)[0-9a-f]{62}/[0-9a-f]{16}/document\.djvu|" - r"objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))|" - r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl|png)|ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|document\.pdf))$" +"""Compatibility import for backend.reader.catalog.domain.assets.""" +import sys +from backend.reader.catalog.domain import assets as _implementation +from backend.reader.catalog.domain.assets import ( + READER_ALLOWED_BUCKETS as READER_ALLOWED_BUCKETS, + READER_ASSET_FILENAMES as READER_ASSET_FILENAMES, + READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, + READER_BUCKET_PATH_RE as READER_BUCKET_PATH_RE, + READER_EBOOK_BUCKET as READER_EBOOK_BUCKET, + decode_reader_assets as decode_reader_assets, ) -READER_EBOOK_BUCKET = "vomebook/reader-assets-v2" -READER_ALLOWED_BUCKETS = {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"} - -def decode_reader_assets( - raw: bytes, - max_compressed_bytes: int = 5 * 1024 * 1024, - max_decompressed_bytes: int = 50 * 1024 * 1024, -) -> dict[str, object]: - if len(raw) > max_compressed_bytes: - raise ValueError("reader assets sidecar is too large") - with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: - decoded = stream.read(max_decompressed_bytes + 1) - if len(decoded) > max_decompressed_bytes: - raise ValueError("reader assets sidecar expands beyond limit") - payload: object = json.loads(decoded) - payload_map = cast(dict[str, object], payload) if isinstance(payload, dict) else None - files = payload_map.get("f") if payload_map is not None and payload_map.get("v") == 1 else None - if not isinstance(files, dict): - raise ValueError("invalid reader assets sidecar") - file_map = cast(dict[object, object], files) - clean: dict[str, dict[str, object]] = {} - for key, raw_entry in file_map.items(): - if not isinstance(key, str) or not isinstance(raw_entry, dict): - continue - entry = cast(dict[str, object], raw_entry) - if entry.get("s") not in (2, 3, 4): - continue - if entry.get("s") == 2: - path = entry.get("p") - mode = entry.get("m") - if not isinstance(path, str) or not isinstance(mode, str) or mode not in READER_ASSET_FILENAMES: - continue - if entry.get("b") not in READER_ALLOWED_BUCKETS: - continue - path_pattern = READER_BUCKET_PATH_RE - image_page_path = bool(re.fullmatch(r"pages/image/(?:jpg|jpeg|png|bmp|tif|tiff|webp)/[0-9a-f]{64}/pages/page-[0-9]{6}\.webp", path)) - valid_filename = (posixpath.basename(path) in READER_ASSET_FILENAMES[mode] - or (mode == "i" and image_page_path) - or (mode == "p" and entry.get("b") == "vomebook/pdf-pages-v2" - and path.endswith("/reading-manifest.json"))) - if ( - not path_pattern.fullmatch(path) - or not valid_filename - ): - continue - chapter_manifest = entry.get("c") - fallback = entry.get("f") - ocr_manifest = entry.get("o") - chapter_bucket = entry.get("cb") - bucket = entry.get("b") - document_path, document_bucket = entry.get("pd"), entry.get("pdb") - if (document_path is not None or document_bucket is not None) and ( - mode != "p" or not path.endswith("/page-manifest.json") - or not isinstance(document_bucket, str) - or document_bucket not in READER_ALLOWED_BUCKETS - or not isinstance(document_path, str) - or not READER_BUCKET_PATH_RE.fullmatch(document_path) - or not document_path.endswith("/document.pdf") - ): - continue - if chapter_manifest is not None and ( - mode not in {"e", "p"} - or not isinstance(chapter_manifest, str) - or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest) - or not chapter_manifest.endswith("/chapter-manifest.json") - ): - continue - if chapter_manifest is not None and chapter_bucket is None: - continue - if chapter_bucket is not None and ( - chapter_bucket != READER_EBOOK_BUCKET or not isinstance(chapter_manifest, str) - or not READER_BUCKET_PATH_RE.fullmatch(chapter_manifest) - or not (chapter_manifest.startswith("ebook-chapters/") - or (chapter_bucket == "vomebook/reader-assets-v2" - and chapter_manifest.startswith("chapters/ebook/"))) - ): - continue - fallback_is_chm = (bucket == READER_EBOOK_BUCKET and isinstance(fallback, str) - and READER_BUCKET_PATH_RE.fullmatch(fallback) - and fallback.endswith("/document.epub")) - if fallback is not None and not fallback_is_chm: - continue - if ocr_manifest is not None and ( - not isinstance(ocr_manifest, str) - or not READER_BUCKET_PATH_RE.fullmatch(ocr_manifest) - or not ocr_manifest.endswith("/ocr-manifest.json") - ): - continue - if entry.get("b") is not None and entry.get("b") not in READER_ALLOWED_BUCKETS: - continue - if entry.get("ob") is not None and entry.get("ob") != "vomebook/pdf-pages-v2": - continue - if bucket == "vomebook/pdf-pages-v2": - if mode == "p" and (not path.endswith(("/page-manifest.json", "/reading-manifest.json", "/document.pdf")) - or not READER_BUCKET_PATH_RE.fullmatch(path)): - continue - clean[key] = { - "s": 2, - "m": mode, - "p": path, - **({"b": bucket} if bucket else {}), - **({"pd": document_path, "pdb": document_bucket} if document_path else {}), - **({"c": chapter_manifest} if chapter_manifest else {}), - **({"cb": chapter_bucket} if chapter_bucket else {}), - **({"f": fallback} if fallback else {}), - **({"o": ocr_manifest} if ocr_manifest else {}), - **({"ob": "vomebook/pdf-pages-v2"} if entry.get("ob") else {}), - **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {}), - } - else: - ocr_manifest = entry.get("o") - if (isinstance(ocr_manifest, str) and READER_BUCKET_PATH_RE.fullmatch(ocr_manifest) - and ocr_manifest.endswith("/ocr-manifest.json")): - clean[key] = {"s": 3, "m": "p", "o": ocr_manifest, "b": "vomebook/pdf-pages-v2", - **({"om": entry.get("om")} if isinstance(entry.get("om"), str) else {})} - else: - clean[key] = {"s": 4} - return {"v": 1, "f": clean} +sys.modules[__name__] = _implementation diff --git a/backend/reader_index.py b/backend/reader_index.py index 381b1e45fc5425df9679e073159babdde1e1094b..2745eb732bfb0d7e11733998ef00163eeddf13a4 100644 --- a/backend/reader_index.py +++ b/backend/reader_index.py @@ -1,54 +1,10 @@ -"""Incremental Reader index construction without publishing partial results.""" - -from collections.abc import Callable -from typing import TypedDict, cast - - -class ReaderIndexBuild(TypedDict): - generation: int - records: list[dict[str, object]] - next: int - indices: list[int] - repos: dict[str, list[int]] - keys: dict[str, int] - ids: dict[str, list[int]] - legacy_ids: dict[str, list[int]] - - -def new_build(generation: int, records: list[dict[str, object]]) -> ReaderIndexBuild: - return {"generation": generation, "records": records, "next": 0, - "indices": [], "repos": {}, "keys": {}, "ids": {}, "legacy_ids": {}} - - -def advance_build(build: ReaderIndexBuild, limit: int, deadline: float, *, - now: Callable[[], float], source_id: Callable[[str], str], - asset_key: Callable[[dict[str, object]], str], - record_link: Callable[[dict[str, object]], str], - dataset_url: Callable[[str, str], str], - reader_extensions: frozenset[str]) -> bool: - """Advance at most one batch; callers own generation checks and publication.""" - end = min(len(build["records"]), build["next"] + limit) - while build["next"] < end: - idx = build["next"] - rec = build["records"][idx] - repo = rec.get("Repo", "") - build["keys"][asset_key(rec)] = idx - current_url = cast(str, rec.get("Link") or record_link(rec)) - build["ids"].setdefault(source_id(current_url), []).append(idx) - # Old links omitted a repeated filename extension; index the historical - # alias without changing the canonical identity or resolving collisions. - name, ext, folders = rec.get("File", ""), rec.get("Extension", ""), rec.get("Folder", []) - if (isinstance(repo, str) and repo.startswith("VoiceOfML/") and isinstance(name, str) - and isinstance(ext, str) and ext and name.lower().endswith("." + ext.lower()) - and isinstance(folders, list) and all(isinstance(part, str) for part in cast(list[object], folders))): - legacy_path = "/".join([*cast(list[str], folders), name]) - legacy_url = dataset_url(repo, legacy_path) - if legacy_url != (rec.get("Link") or record_link(rec)): - build["legacy_ids"].setdefault(source_id(legacy_url), []).append(idx) - if rec.get("_ext_lower", "") in reader_extensions: - build["indices"].append(idx) - build["repos"].setdefault(cast(str, repo), []).append(idx) - build["next"] += 1 - if now() >= deadline: - break - return build["next"] >= len(build["records"]) +"""Compatibility import for backend.reader.catalog.domain.index.""" +import sys +from backend.reader.catalog.domain import index as _implementation +from backend.reader.catalog.domain.index import ( + ReaderIndexBuild as ReaderIndexBuild, + advance_build as advance_build, + new_build as new_build, +) + +sys.modules[__name__] = _implementation diff --git a/backend/reader_ocr.py b/backend/reader_ocr.py index f1e40636bf9a7d9db3d044d513b3794f181fe442..05571c032ed8c67510224f1b16fd1bcc6ecb0926 100644 --- a/backend/reader_ocr.py +++ b/backend/reader_ocr.py @@ -1,165 +1,13 @@ -"""Bounded PDF text-index validation and original-offset search.""" -from __future__ import annotations - -from array import array -import gzip -import io -import json -import re -from typing import NotRequired, TypedDict, cast - - -class OcrSpan(TypedDict): - start: int - end: int - box: list[int | float] - - -class OcrPage(TypedDict): - page: int - text: str - folded: str - fold_map: NotRequired[array[int] | None] - layout: dict[str, object] - spans: list[OcrSpan] - - -class OcrSearchHit(TypedDict): - page: int - start: int - length: int - snippet: str - snippet_start: int - boxes: list[list[int | float]] - - -def fold_reader_ocr_text(text: str) -> tuple[str, array[int] | None]: - """Map casefold-expanded code points back to the source text.""" - folded = text.casefold() - if len(folded) == len(text): - return folded, None - pieces: list[str] = [] - fold_map: array[int] = array('I') - for index, character in enumerate(text): - piece = character.casefold() - pieces.append(piece) - fold_map.extend([index] * len(piece)) - return "".join(pieces), fold_map - - -def parse_reader_ocr_book(raw: bytes, max_bytes: int) -> tuple[list[OcrPage], int]: - """Decode and validate one v2 book index without exceeding its byte limit.""" - with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: - decoded = stream.read(max_bytes + 1) - if len(decoded) > max_bytes: - raise ValueError("PDF OCR text index is too large") - payload: object = json.loads(decoded) - if not isinstance(payload, dict): - raise ValueError("invalid PDF OCR text index") - document = cast(dict[str, object], payload) - raw_pages = document.get("pages") - if not isinstance(raw_pages, list): - raise ValueError("invalid PDF OCR text index") - pages = cast(list[object], raw_pages) - if (len(pages) > 200000 - or document.get("version") != 2 or document.get("kind") != "pdf-book-text" - or document.get("complete") is not True - or document.get("offset_unit") != "unicode-codepoint" - or document.get("page_count") != len(pages) - or not re.fullmatch(r"[0-9a-f]{64}", str(document.get("source_sha256", "")))): - raise ValueError("invalid PDF OCR text index") - output: list[OcrPage] = [] - total_bytes = 0 - previous = 0 - for raw_page in pages: - if not isinstance(raw_page, dict): - raise ValueError("invalid PDF OCR text page") - item = cast(dict[str, object], raw_page) - number, text = item.get("page"), item.get("text") - if (not isinstance(number, int) or number < 1 or number <= previous - or not isinstance(text, str)): - raise ValueError("invalid PDF OCR text page") - total_bytes += len(text.encode("utf-8")) - if total_bytes > max_bytes: - raise ValueError("PDF OCR text index is too large") - layout, spans = item.get("layout"), item.get("text_spans") - if (not isinstance(layout, dict) or cast(dict[str, object], layout).get("offset_unit") != "unicode-codepoint" - or not isinstance(spans, list)): - raise ValueError("invalid PDF text layout mapping") - previous_span_end = 0 - for raw_span in cast(list[object], spans): - if not isinstance(raw_span, dict): - raise ValueError("invalid PDF text span") - span = cast(dict[str, object], raw_span) - start, end, box = span.get("start"), span.get("end"), span.get("box") - if (not isinstance(start, int) or not isinstance(end, int) or start < previous_span_end - or end <= start or end > len(text) or not isinstance(box, list)): - raise ValueError("invalid PDF text span") - values = cast(list[object], box) - if len(values) != 4 or any(not isinstance(value, (int, float)) or value < 0 or value > 1 - for value in values): - raise ValueError("invalid PDF text span") - previous_span_end = end - folded, fold_map = fold_reader_ocr_text(text) - if fold_map is not None: - total_bytes += len(fold_map) * fold_map.itemsize - output.append({"page": number, "text": text, "folded": folded, "fold_map": fold_map, - "layout": cast(dict[str, object], layout), "spans": cast(list[OcrSpan], spans)}) - previous = number - return output, total_bytes - - -def search_reader_ocr_pages( - pages: list[OcrPage], needle: str, page: int, page_size: int -) -> tuple[int, list[OcrSearchHit]]: - """Count all non-overlapping matches; return one page in original offsets.""" - offset = (page - 1) * page_size - end_offset = offset + page_size - folded_length = len(needle) - total = 0 - results: list[OcrSearchHit] = [] - if not folded_length: - return total, results - # Once the requested page is full, only the remaining count is needed. - # Exact built-ins keep custom string methods and unusual callers on the - # existing per-match path, including their errors and side effects. - count_safe = type(needle) is str and type(page) is int and type(page_size) is int and page_size > 0 - for item in pages: - text, folded = item["text"], item["folded"] - if "fold_map" in item: - fold_map = item["fold_map"] - elif len(folded) == len(text): - fold_map = None - else: - folded, fold_map = fold_reader_ocr_text(text) - if count_safe and len(results) == page_size and type(folded) is str: - total += folded.count(needle) - continue - start = 0 - while True: - found = folded.find(needle, start) - if found < 0: - break - match_index = total - total += 1 - if offset <= match_index < end_offset: - if fold_map is None: - original_start, original_end = found, found + folded_length - else: - original_start = fold_map[found] - original_end = fold_map[found + folded_length - 1] + 1 - snippet_start = max(0, original_start - 72) - snippet_end = min(len(text), original_end + 88) - boxes = [span["box"] for span in item["spans"] - if span["end"] > original_start and span["start"] < original_end] - results.append({ - "page": item["page"], "start": original_start, - "length": original_end - original_start, - "snippet": text[snippet_start:snippet_end], - "snippet_start": original_start - snippet_start, "boxes": boxes, - }) - if count_safe and len(results) == page_size and type(folded) is str: - total += folded.count(needle, found + folded_length) - break - start = found + folded_length - return total, results +"""Compatibility import for backend.reader.query.domain.ocr.""" +import sys +from backend.reader.query.domain import ocr as _implementation +from backend.reader.query.domain.ocr import ( + OcrPage as OcrPage, + OcrSearchHit as OcrSearchHit, + OcrSpan as OcrSpan, + fold_reader_ocr_text as fold_reader_ocr_text, + parse_reader_ocr_book as parse_reader_ocr_book, + search_reader_ocr_pages as search_reader_ocr_pages, +) + +sys.modules[__name__] = _implementation diff --git a/backend/reader_range_cache.py b/backend/reader_range_cache.py index 15c1afaa1c133a89515c29988204b14e43dd1497..2aaf5f4a98ff5a2eba612581f1006794219e8138 100644 --- a/backend/reader_range_cache.py +++ b/backend/reader_range_cache.py @@ -1,67 +1,12 @@ -"""Safe exact-byte subrange reuse for the Reader proxy's bounded cache.""" -from __future__ import annotations - -from collections import OrderedDict -from collections.abc import Callable -from typing import Protocol -import re - -RangeKey = tuple[str, str, int | None, str | None] -RangeCacheEntry = tuple[float, bytes, dict[str, str]] - - -class RangeCacheState(Protocol): - reader_range_cache: OrderedDict[RangeKey, RangeCacheEntry] - reader_range_cache_bytes: int - - -def requested_range_bounds(header: str | None, total: int) -> tuple[int, int] | None: - """Resolve an ordinary single byte range; unknown/unsatisfiable forms return None.""" - if header is None or total <= 0: - return None - match = re.fullmatch(r"bytes=([0-9]{0,20})-([0-9]{0,20})", header) - if match is None: - return None - first, last = match.groups() - if not first: - if not last or int(last) == 0: - return None - return max(0, total - int(last)), total - 1 - start = int(first) - end = min(int(last), total - 1) if last else total - 1 - if start > end: - return None - return start, end - - -def cached_subrange(range_key: RangeKey, get_state: Callable[[], RangeCacheState], - get_limit: Callable[[], int], get_ttl: Callable[[], int], - now: Callable[[], float]) -> tuple[bytes, dict[str, str]] | None: - """Serve a verified contained range, evicting stale entries in LRU order.""" - requested = re.fullmatch(r"bytes=([0-9]{1,20})-([0-9]{1,20})", range_key[1]) - if requested is None: - return None - start, end = (int(value) for value in requested.groups()) - if start > end or end - start + 1 > get_limit(): - return None - cache = get_state().reader_range_cache - current_time = now() - for key in reversed(list(cache)): - cached_at, payload, headers = cache[key] - if current_time - cached_at >= get_ttl(): - cache.pop(key) - get_state().reader_range_cache_bytes -= len(payload) - continue - if key[0] != range_key[0] or key[2:] != range_key[2:]: - continue - match = re.fullmatch(r"bytes ([0-9]+)-([0-9]+)/([0-9]+)", headers.get("Content-Range", "")) - if match is None: - continue - cached_start, cached_end, total = (int(value) for value in match.groups()) - final_end = min(end, total - 1) - if cached_start <= start <= final_end <= cached_end and len(payload) == cached_end - cached_start + 1: - cache.move_to_end(key) - body = payload[start - cached_start:final_end - cached_start + 1] - return body, {**headers, "Content-Range": f"bytes {start}-{final_end}/{total}", - "Content-Length": str(len(body))} - return None +"""Compatibility import for backend.reader.document.domain.range_cache.""" +import sys +from backend.reader.document.domain import range_cache as _implementation +from backend.reader.document.domain.range_cache import ( + RangeCacheEntry as RangeCacheEntry, + RangeCacheState as RangeCacheState, + RangeKey as RangeKey, + cached_subrange as cached_subrange, + requested_range_bounds as requested_range_bounds, +) + +sys.modules[__name__] = _implementation diff --git a/backend/reader_v3_catalog.py b/backend/reader_v3_catalog.py index 378bd69e95c771e77599196bd1c1ef5e8a289948..ba52d55fdaa91746f2b11b0ae7280afdf8e5899b 100644 --- a/backend/reader_v3_catalog.py +++ b/backend/reader_v3_catalog.py @@ -1,161 +1,18 @@ -"""Pinned v3 catalog projection, using only canonical bucket metadata URLs.""" -import asyncio -import hashlib -import json -import re -from typing import Callable, Literal, ParamSpec, TypeVar, cast, overload - -import aiohttp - -from backend.upstream_http import open_download_response, validate_fixed_source_redirect_url - -BUCKET = "vomebook/reader-assets-v2" -BASE = f"https://huggingface.co/buckets/{BUCKET}/resolve/" -POINTER = "reader-index/v3/current.json" -MAX_BYTES = 8 * 1024 * 1024 - - -def sha(value: object) -> re.Match[str] | bool | None: - return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value) - - -def catalog_path(generation: object) -> str: - if not sha(generation): - raise ValueError("invalid v3 catalog generation") - return f"reader-index/v3/generations/{generation}/catalog.json" - - -def decode_catalog(pointer: dict[str, object], raw: bytes) -> dict[str, object]: - from backend.reader_assets import READER_BUCKET_PATH_RE - if pointer.get("version") != 1 or pointer.get("kind") != "reader-reading-pointer": - raise ValueError("invalid v3 pointer") - generation = pointer.get("generation") - ref = cast(dict[str, object], pointer.get("catalog", {})) - if (ref.get("bucket") != BUCKET or ref.get("path") != catalog_path(generation) - or ref.get("role") != "runtime" or type(ref.get("bytes")) is not int - or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES or not sha(ref.get("sha256")) - or len(raw) != ref["bytes"] or hashlib.sha256(raw).hexdigest() != ref["sha256"]): - raise ValueError("v3 catalog resource mismatch") - catalog = cast(dict[str, object], json.loads(raw)) - body = {k: v for k, v in catalog.items() if k != "generation"} - digest = hashlib.sha256(json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"), - allow_nan=False).encode()).hexdigest() - if (catalog.get("version") != 3 or catalog.get("kind") != "reader-reading-catalog" - or catalog.get("generation") != generation or digest != generation - or not isinstance(catalog.get("files"), dict)): - raise ValueError("invalid v3 catalog identity") - overrides: dict[str, dict[str, object]] = {} - for key, raw_entry in cast(dict[object, object], catalog["files"]).items(): - if not isinstance(key, str) or not key or not isinstance(raw_entry, dict): - raise ValueError("invalid v3 source key") - entry = cast(dict[str, object], raw_entry) - resource = cast(dict[str, object], entry.get("resource", {})) - source = entry.get("source_sha256") - path = resource.get("path", "") - if (not isinstance(source, str) or not sha(source) or not sha(entry.get("reading_generation")) - or resource.get("bucket") != "vomebook/pdf-pages-v2" or resource.get("role") != "runtime" - or not isinstance(path, str) or not READER_BUCKET_PATH_RE.fullmatch(path) - or not path.startswith(f"objects/{source[:2]}/{source}/") - or not path.endswith("/reading-manifest.json") or not sha(resource.get("sha256")) - or type(resource.get("bytes")) is not int or cast(int, resource["bytes"]) < 1): - raise ValueError("invalid v3 reading reference") - overrides[key] = {"s": 2, "m": "p", "p": path, "b": resource["bucket"]} - return {"generation": generation, "catalog_sha256": ref["sha256"], - "files": overrides, "catalog": ref, - **({"base_sidecar_ref": catalog["base_sidecar"]} if catalog.get("base_sidecar") else {})} - - -def validate_base_ref(ref: object) -> dict[str, object]: - if not isinstance(ref, dict): - raise ValueError("invalid unified base sidecar") - ref = cast(dict[str, object], ref) - if (ref.get("bucket") != BUCKET or ref.get("role") != "runtime" - or not sha(ref.get("sha256")) or ref.get("path") != - f"reader-index/snapshots/{ref['sha256']}/reader_assets.json.gz" - or type(ref.get("bytes")) is not int or not 1 <= cast(int, ref["bytes"]) <= MAX_BYTES): - raise ValueError("invalid unified base sidecar") - return ref - - -_DecodeParams = ParamSpec("_DecodeParams") -_DecodeResult = TypeVar("_DecodeResult") - - -async def decode_in_thread(func: Callable[_DecodeParams, _DecodeResult], - *args: _DecodeParams.args, **kwargs: _DecodeParams.kwargs) -> _DecodeResult: - # Keep the refresh owner alive until its worker exits even after cancellation. - # Otherwise a subsequent refresh could start another large decode while the - # abandoned worker still holds its inputs and intermediate objects. - task = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs)) - try: - return await asyncio.shield(task) - except asyncio.CancelledError: - while not task.done(): - try: - await asyncio.shield(task) - except asyncio.CancelledError: - continue - except Exception: - break - if not task.cancelled(): - task.exception() # Retrieve a worker failure without replacing cancellation. - raise - - -async def load_reading_catalog(session: object) -> dict[str, object] | None: - @overload - async def fetch(path: str, *, missing: Literal[True]) -> bytes | None: ... - - @overload - async def fetch(path: str, *, missing: Literal[False] = False) -> bytes: ... - - async def fetch(path: str, *, missing: bool = False) -> bytes | None: - source_url = BASE + path - # Validate every redirect hop against the fixed URL or signed storage; - # metadata is mutable, so its signed targets are never reused. - response = await open_download_response( - session, source_url, aiohttp.ClientTimeout(total=20, connect=8, sock_read=10), - request_headers={"Cache-Control": "no-cache"}, - url_validator=lambda url: validate_fixed_source_redirect_url(url, source_url), - cache_redirects=False, - ) - try: - if missing and response.status == 404: - return None - if response.status != 200: - raise RuntimeError(f"v3 metadata HTTP {response.status}") - raw = bytearray() - async for chunk in response.content.iter_chunked(64 * 1024): - raw.extend(chunk) - if len(raw) > MAX_BYTES: - raise ValueError("v3 metadata exceeds limit") - return bytes(raw) - finally: - response.release() - raw = await fetch(POINTER, missing=True) - if raw is None: - return None - pointer = cast(dict[str, object], json.loads(raw)) - # Validate the exact fixed catalog path before starting another request. - path = catalog_path(pointer.get("generation")) - if cast(dict[str, object], pointer.get("catalog", {})).get("path") != path: - raise ValueError("v3 pointer path mismatch") - catalog = await fetch(path) - result = await decode_in_thread(decode_catalog, pointer, catalog) - if result.get("base_sidecar_ref"): - ref = validate_base_ref(result["base_sidecar_ref"]) - packed = await fetch(cast(str, ref["path"])) - if len(packed) != ref["bytes"] or hashlib.sha256(packed).hexdigest() != ref["sha256"]: - raise ValueError("unified base sidecar checksum mismatch") - from backend.reader_assets import decode_reader_assets - result["base_sidecar"] = await decode_in_thread(decode_reader_assets, packed) - return result - - -def merge_sidecar(base: dict[str, object], catalog: dict[str, object] | None) -> dict[str, object]: - if not catalog: - return base - base = cast(dict[str, object], catalog.get("base_sidecar", base)) - return {**base, "f": {**cast(dict[str, object], base["f"]), **cast(dict[str, object], catalog["files"])}, - "v3": {"generation": catalog["generation"], "catalog_sha256": catalog["catalog_sha256"], - "files": len(cast(dict[str, object], catalog["files"]))}} +"""Compatibility import for backend.reader.catalog.infrastructure.v3.""" +import sys +from backend.reader.catalog.infrastructure import v3 as _implementation +from backend.reader.catalog.infrastructure.v3 import ( + BASE as BASE, + BUCKET as BUCKET, + MAX_BYTES as MAX_BYTES, + POINTER as POINTER, + catalog_path as catalog_path, + decode_catalog as decode_catalog, + decode_in_thread as decode_in_thread, + load_reading_catalog as load_reading_catalog, + merge_sidecar as merge_sidecar, + sha as sha, + validate_base_ref as validate_base_ref, +) + +sys.modules[__name__] = _implementation diff --git a/backend/record_metadata.py b/backend/record_metadata.py index 67542a8c94a04e658119fcb5ad8927a392d12c87..64e0080637eed1df60e6b797c9a389a5f6d4ffc3 100644 --- a/backend/record_metadata.py +++ b/backend/record_metadata.py @@ -1,185 +1,23 @@ -"""Pure record paths and reader projections shared by search and reader APIs.""" -import posixpath -import re -from typing import cast -from urllib.parse import quote - - -READER_ASSET_MODES = { - "p": "pdf", "e": "epub", "d": "docx", "h": "html", - "t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video", "f": "swf", -} -READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"}) - - -def build_record_relative_path(rec: dict[str, object]) -> str: - file_name = cast(str, rec.get("File", "")) - extension = cast(str, rec.get("Extension", "")) - full_name = f"{file_name}.{extension}" if extension else file_name - folders = cast(list[str], rec.get("Folder", []) or []) - return posixpath.join(*folders, full_name) if folders else full_name - - -def build_reader_asset_key(rec: dict[str, object]) -> str: - return f"{rec.get('Repo', '')}\0{build_record_relative_path(rec)}" - - -def dataset_file_url(repo: str, relative_path: str, action: str = "resolve") -> str: - return f"https://huggingface.co/datasets/{repo}/{action}/main/{quote(relative_path, safe='/')}" - - -def dataset_file_urls(repo: str, relative_path: str) -> tuple[str, str]: - """Produce source and browser URLs using the same encoded path.""" - encoded = quote(relative_path, safe="/") - prefix = f"https://huggingface.co/datasets/{repo}" - return f"{prefix}/resolve/main/{encoded}", f"{prefix}/blob/main/{encoded}" - - -def build_record_link(rec: dict[str, object]) -> str: - return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec)) - - -def build_record_path_url(rec: dict[str, object]) -> str: - return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec), "blob") - - -def build_browser_file_name(file_item: dict[str, object]) -> str: - name = str(file_item.get("name", "") or "file") - ext = str(file_item.get("ext", "") or "") - # Browser metadata stores the source record's stem and last extension in - # separate fields; a repeated suffix in the stem is still significant. - if not ext: - return name - return f"{name}.{ext}" - - -def enrich_browser_entry(repo: str, path: str, entry: dict[str, object]) -> dict[str, object]: - decoded = dict(entry or {}) - decoded["current_path"] = decoded.get("current_path", path) - folders: list[dict[str, object]] = [] - for folder in cast(list[dict[str, object]], decoded.get("folders", []) or []): - item = dict(folder) - if "path" not in item: - name = item.get("name", "") - item["path"] = f"{path}/{name}" if path else name - folders.append(item) - files: list[dict[str, object]] = [] - for file_item in cast(list[dict[str, object]], decoded.get("files", []) or []): - item = dict(file_item) - full_name = build_browser_file_name(item) - rel_path = f"{path}/{full_name}" if path else full_name - if not item.get("link") and not item.get("path"): - item["link"], item["path"] = dataset_file_urls(repo, rel_path) - else: - item["link"] = item.get("link") or dataset_file_url(repo, rel_path) - item["path"] = item.get("path") or dataset_file_url(repo, rel_path, "blob") - files.append(item) - decoded["folders"] = folders - decoded["files"] = files - return decoded - - -def reader_asset_url(asset: dict[str, object]) -> str: - path = quote(str(asset.get("p") or ""), safe="/") - return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + path - - -def reader_extension_for_asset(asset: dict[str, object], original_extension: str = "") -> str: - asset_path = str(asset.get("p") or "") - if asset.get('c'): - return 'epub-chapters' - if asset_path.endswith(("page-manifest.json", "reading-manifest.json")): - return "image-pages" if asset.get("m") == "i" else "pdf-pages" - if asset.get("m") == "e": - match = re.search(r"/(?:document|book)\.(epub|mobi|azw|azw3|fb2)$", asset_path, re.IGNORECASE) - if match: - return match.group(1).lower() - extension = str(original_extension or "").lower().lstrip(".") - return extension if extension in READER_NATIVE_FOLIATE_EXTENSIONS else "epub" - mode = asset.get("m") - return READER_ASSET_MODES.get(mode, "") if isinstance(mode, str) else "" - - -def _reader_bucket_url(path: str) -> str: - return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + quote(path, safe="/") - - -def reader_asset_fields(asset: dict[str, object], original_extension: str) -> dict[str, str]: - ocr_path = str(asset.get("o") or "") - ocr_bucket = asset.get("b") == "vomebook/pdf-pages-v2" or asset.get("ob") == "vomebook/pdf-pages-v2" - fields: dict[str, str] = {} - if ocr_path.endswith("/ocr-manifest.json") and ocr_bucket: - fields["ocr_manifest"] = _reader_bucket_url(ocr_path) - fields["ocr_mode"] = str(asset.get("om") or "") - if asset.get("s") == 3: - return fields - if asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"): - return fields - if str(original_extension).lower().lstrip('.') == 'djvu': - # Existing OCR remains independent. Native DjVu reading starts at the - # dataset source, never an older image stream, manifest or derivative. - return fields - if (asset.get('m') == 'p' and not asset.get('c') and str(asset['p']).endswith('/page-manifest.json') - and str(original_extension).lower().lstrip('.') != 'djvu'): - # Legacy page indexes no longer own PDF/converted-PDF reading. Keep - # independent OCR metadata and prefer the validated PDF companion. - if asset.get('pd') and asset.get('pdb') in {'vomebook/reader-assets-v2', 'vomebook/pdf-pages-v2'}: - fields.update(url=_reader_bucket_url(cast(str, asset['pd'])), extension='pdf') - return fields - fields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)}) - if asset.get("pd") and asset.get("pdb") in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}: - fields["pdf_document"] = _reader_bucket_url(cast(str, asset["pd"])) - if asset.get("c"): - if asset.get("cb") == "vomebook/reader-assets-v2": - fields["chapter_manifest"] = _reader_bucket_url(cast(str, asset["c"])) - elif asset.get("cb") == "vomebook/pdf-pages-v2": - fields["chapter_manifest"] = "/api/reader-bucket-resource?path=" + quote(cast(str, asset["c"]), safe="/") - return fields - - -def enrich_reader_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]: - result = dict(record) - fields = reader_asset_fields(asset, cast(str, record.get("Extension", ""))) - direct_modes = { - "pdf": ("pdf", "pdf"), "djvu": ("djvu", "pdf"), "vcf": ("vcf", "text"), "ini": ("ini", "text"), - "tif": ("image", "image"), "tiff": ("image", "image"), - } - direct_extension = str(record.get("Extension") or "").lower().lstrip(".") - if 'url' not in fields and direct_extension in direct_modes: - # A PDF without a converted/page asset remains directly readable from - # its immutable source dataset after the derived asset store changes. - fields.update(url=cast(str, record.get("Link") or build_record_link(record)), - extension=direct_modes[direct_extension][0]) - if fields: - for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"), - ("chapter_manifest", "ReaderChapterManifest"), - ("ocr_manifest", "ReaderOcrManifest"), ("ocr_mode", "ReaderOcrMode"), - ("pdf_document", "ReaderPdfDocument")): - if source in fields: - result[target] = fields[source] - result["DownloadLink"] = record.get("Link") or build_record_link(record) - return result - - -def add_reader_assets(payload: dict[str, object], assets: dict[str, object]) -> dict[str, object]: - files = cast(dict[str, dict[str, object]], assets.get("f", {})) - return {**payload, "results": [ - enrich_reader_record(record, files.get(build_reader_asset_key(record), {})) - for record in cast(list[dict[str, object]], payload.get("results", [])) - ]} - - -def reader_resolved_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]: - source = record.get("Link") or build_record_link(record) - extension = str(record.get("Extension") or "").lower().lstrip(".") - repo = cast(str, record.get("Repo", "")).split("/")[-1] - folders = [str(item) for item in cast(list[object], record.get("Folder", []))] - return { - "url": source, "download": source, "extension": extension, - "original_extension": extension, "title": record.get("File") or record.get("Name") or "在线阅读", - # Keep the exact indexed filename separate from the display title. - # The stem may itself end in an extension, or include trailing spaces. - "filename": build_record_relative_path(record).rsplit("/", 1)[-1], - "path": "/".join([repo, *folders]), "folder": "/".join(folders), "repo": repo, - **reader_asset_fields(asset, extension), - } +"""Compatibility import for backend.search.corpus.domain.records.""" +import sys +from backend.search.corpus.domain import records as _implementation +from backend.search.corpus.domain.records import ( + READER_ASSET_MODES as READER_ASSET_MODES, + READER_NATIVE_FOLIATE_EXTENSIONS as READER_NATIVE_FOLIATE_EXTENSIONS, + add_reader_assets as add_reader_assets, + build_browser_file_name as build_browser_file_name, + build_reader_asset_key as build_reader_asset_key, + build_record_link as build_record_link, + build_record_path_url as build_record_path_url, + build_record_relative_path as build_record_relative_path, + dataset_file_url as dataset_file_url, + dataset_file_urls as dataset_file_urls, + enrich_browser_entry as enrich_browser_entry, + enrich_reader_record as enrich_reader_record, + reader_asset_fields as reader_asset_fields, + reader_asset_url as reader_asset_url, + reader_extension_for_asset as reader_extension_for_asset, + reader_resolved_record as reader_resolved_record, +) + +sys.modules[__name__] = _implementation diff --git a/backend/runtime/application/lifecycle.py b/backend/runtime/application/lifecycle.py index 6c385f9cabfc3e87dfafbea59b6c763e93280522..51d77cbf7f0cbc92d674ac757711e8a0510fc03a 100644 --- a/backend/runtime/application/lifecycle.py +++ b/backend/runtime/application/lifecycle.py @@ -9,8 +9,8 @@ from typing import Any, Literal, Protocol import aiohttp from backend.reader.document.application.ranges import RangeFlightState -from backend.reader_range_cache import RangeCacheState -from backend.search_execution import SearchExecutor +from backend.reader.document.domain.range_cache import RangeCacheState +from backend.search.infrastructure.executor import SearchExecutor class LifecycleState(RangeCacheState, RangeFlightState, Protocol): diff --git a/backend/search/application/bootstrap.py b/backend/search/application/bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..ac5a8beda523c9f3ee14d88b5f3e82765705989c --- /dev/null +++ b/backend/search/application/bootstrap.py @@ -0,0 +1,31 @@ +"""Typed construction of initial search pages from caller-owned state.""" +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping, Sequence + +SearchRecord = dict[str, object] + + +def trim_initial_results(raw: Iterable[SearchRecord]) -> list[SearchRecord]: + return [{"Repo": record.get("Repo", ""), "File": record.get("File", ""), + "Extension": record.get("Extension", ""), "Folder": record.get("Folder", []), + "Size": record.get("Size", ""), "HasTxt": record.get("HasTxt", "")} for record in raw] + + +def build_initial_payload(repo: str | None, get_page_size: Callable[[], int], + get_repos: Callable[[], Mapping[str, Sequence[int]]], + get_records: Callable[[], Sequence[SearchRecord]], + get_trim: Callable[[], Callable[[Sequence[SearchRecord]], list[SearchRecord]]], + get_generation: Callable[[], Callable[[], str]]) -> dict[str, object]: + """Preserve snapshot lookup, projection and generation evaluation order.""" + if repo: + indices = get_repos().get(repo, []) + result_records = [get_records()[index] for index in indices[:get_page_size()]] + mode = "repo" + total = len(indices) + else: + result_records = get_records()[:get_page_size()] + mode = "global" + total = len(get_records()) + return {"mode": mode, "repo": repo, "sort": "relevance", "page": 1, "page_size": get_page_size(), + "total": total, "results": get_trim()(result_records), "generation": get_generation()()} diff --git a/backend/search/corpus/application/preparation.py b/backend/search/corpus/application/preparation.py index 6444b6e511dc50b7134161d39a693a8025bce72b..c71fca46a5e157eec4744528cd6ff7867dd673dc 100644 --- a/backend/search/corpus/application/preparation.py +++ b/backend/search/corpus/application/preparation.py @@ -8,8 +8,8 @@ from collections.abc import Callable, Iterable from dataclasses import dataclass from pathlib import Path -from backend.data_formats import CompactTreeNode, CompactBrowserEntry -from backend.search_indexes import PostingIndex +from backend.search.corpus.domain.formats import CompactTreeNode, CompactBrowserEntry +from backend.search.corpus.infrastructure.indexes import PostingIndex from backend.search.corpus.domain.metadata import Record Tree = dict[str, list[Record]] diff --git a/backend/search/corpus/domain/folder_contents.py b/backend/search/corpus/domain/folder_contents.py new file mode 100644 index 0000000000000000000000000000000000000000..c205ffbcc2b8ae60f9c245a5a21c4c5e9335f243 --- /dev/null +++ b/backend/search/corpus/domain/folder_contents.py @@ -0,0 +1,84 @@ +"""Directory browser lookup against a caller-owned search index snapshot.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from typing import cast + +SearchRecord = dict[str, object] +BrowserEntries = Mapping[str, Mapping[str, SearchRecord]] +FolderIndex = Mapping[str, Mapping[str, Sequence[int]]] +RepoIndices = Mapping[str, Sequence[int]] + + +def get_folder_contents(repo: str, path: str, *, + get_browser: Callable[[], BrowserEntries], + get_folder_index: Callable[[], FolderIndex], + get_repo_indices: Callable[[], RepoIndices], + get_records: Callable[[], Sequence[SearchRecord]], + enrich_browser_entry: Callable[[str, str, SearchRecord], SearchRecord], + build_record_link: Callable[[SearchRecord], str], + build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord: + """Prefer precomputed entries, otherwise count and project the indexed subtree.""" + if repo in get_browser(): + repo_browser = get_browser().get(repo, {}) or {} + if path in repo_browser: + return enrich_browser_entry(repo, path, repo_browser[path]) + if path == "" and "" in repo_browser: + return enrich_browser_entry(repo, path, repo_browser[""]) + return _from_index(repo, path, get_folder_index, get_repo_indices, get_records, + build_record_link, build_record_path_url) + + +def _from_index(repo: str, path: str, get_folder_index: Callable[[], FolderIndex], + get_repo_indices: Callable[[], RepoIndices], get_records: Callable[[], Sequence[SearchRecord]], + build_record_link: Callable[[SearchRecord], str], + build_record_path_url: Callable[[SearchRecord], str]) -> SearchRecord: + path_parts = [p for p in path.strip("/").split("/") if p] + path_depth = len(path_parts) + repo_folders = get_folder_index().get(repo) + candidate_indices = (repo_folders.get("/".join(path_parts), []) + if repo_folders is not None else get_repo_indices().get(repo, [])) + + def is_under(rec_folders: list[str], prefix: list[str]) -> bool: + return rec_folders[:len(prefix)] == prefix + matching = [get_records()[i] for i in candidate_indices + if is_under(cast(list[str], get_records()[i].get("Folder", []) or []), path_parts)] + result_folders = _subfolder_results(matching, path_parts, path_depth) + direct_files = _direct_file_results(matching, path_depth, build_record_link, build_record_path_url) + return {"folders": result_folders, "files": direct_files, "current_path": path} + + +def _subfolder_results(matching: Sequence[SearchRecord], path_parts: list[str], + path_depth: int) -> list[SearchRecord]: + subfolder_names: set[str] = set() + subfolder_counts: dict[str, int] = {} + for rec in matching: + folders = cast(list[str], rec.get("Folder", []) or []) + if len(folders) > path_depth: + name = folders[path_depth] + subfolder_names.add(name) + subfolder_counts[name] = subfolder_counts.get(name, 0) + 1 + result_folders: list[SearchRecord] = [] + for fname in sorted(subfolder_names): + full_path = "/".join(path_parts + [fname]) if path_parts else fname + result_folders.append({"name": fname, "path": full_path, "count": subfolder_counts.get(fname, 0)}) + return result_folders + + +def _direct_file_results(matching: Sequence[SearchRecord], path_depth: int, + build_record_link: Callable[[SearchRecord], str], + build_record_path_url: Callable[[SearchRecord], str]) -> list[SearchRecord]: + direct_files: list[SearchRecord] = [] + for rec in matching: + folders = cast(list[str], rec.get("Folder", []) or []) + if len(folders) == path_depth: + direct_files.append({ + "name": rec.get("File", ""), + "ext": rec.get("Extension", ""), + "link": rec.get("Link") or build_record_link(rec), + "path": rec.get("Path") or build_record_path_url(rec), + "hasTxt": rec.get("HasTxt", False), + "size": rec.get("Size", ""), + }) + direct_files.sort(key=lambda f: cast(str, f["name"])) + return direct_files diff --git a/backend/search/corpus/domain/folder_tree.py b/backend/search/corpus/domain/folder_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..f8457211ed6268010b79b302313d7cfb37e10897 --- /dev/null +++ b/backend/search/corpus/domain/folder_tree.py @@ -0,0 +1,69 @@ +"""Build search filter trees from a caller-owned index snapshot.""" +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import NotRequired, TypedDict, cast + + +class FolderTreeNode(TypedDict): + name: str + path: str + children: list[FolderTreeNode] + count: int + hasDirectFiles: bool + hasChildren: bool + showSelfToggle: bool + isRoot: NotRequired[bool] + + +def build_folder_tree(repo: str, folder_index: Mapping[str, Mapping[str, Sequence[int]]], + repo_records_map: Mapping[str, Sequence[int]], + records: Sequence[dict[str, object]]) -> list[FolderTreeNode]: + """Preserve corpus counts, stable child order and direct-file toggles.""" + if repo not in folder_index: + return [] + repo_name_short = repo.split("/")[-1] + tree_root: FolderTreeNode = { + "name": repo_name_short, + "path": "", + "children": [], + "count": 0, + "hasDirectFiles": False, + "hasChildren": False, + "showSelfToggle": False, + "isRoot": True, + } + node_map: dict[str, FolderTreeNode] = {"": tree_root} + for path, idx_list in folder_index[repo].items(): + if path == "": + tree_root["count"] = len(idx_list) + continue + parts = path.split("/") + for depth in range(1, len(parts) + 1): + key = "/".join(parts[:depth]) + if key not in node_map: + parent_key = "/".join(parts[:depth - 1]) if depth > 1 else "" + parent = node_map[parent_key] + node: FolderTreeNode = { + "name": parts[depth - 1], + "path": key, + "children": [], + "count": 0, + "hasDirectFiles": False, + "hasChildren": False, + "showSelfToggle": False, + } + node_map[key] = node + parent["children"].append(node) + node_map[path]["count"] = len(idx_list) + direct_file_dirs: set[str] = set() + for idx in repo_records_map.get(repo, []): + rec = records[idx] + folders = cast(list[str], rec.get("Folder", []) or []) + direct_file_dirs.add("/".join(folders)) + for path_key, node in node_map.items(): + node["hasDirectFiles"] = path_key in direct_file_dirs + node["children"].sort(key=lambda child: child["name"]) + node["hasChildren"] = len(node["children"]) > 0 + node["showSelfToggle"] = bool(path_key and node["hasDirectFiles"] and node["hasChildren"]) + return [tree_root] diff --git a/backend/search/corpus/domain/formats.py b/backend/search/corpus/domain/formats.py new file mode 100644 index 0000000000000000000000000000000000000000..277d55a05535a4d9505231ac5f04813c5ff44a20 --- /dev/null +++ b/backend/search/corpus/domain/formats.py @@ -0,0 +1,110 @@ +"""Decode the current compact corpus and directory formats without runtime state.""" + +from typing import TypedDict, cast + + +class CompactCorpus(TypedDict, total=False): + rp: list[str] + fd: list[list[str]] + rc: list[object] + + +class CompactTreeNode(TypedDict, total=False): + n: str + c: int + df: bool + ch: list["CompactTreeNode"] + + +class CompactFolder(TypedDict, total=False): + n: str + c: int + + +class CompactFile(TypedDict, total=False): + n: str + e: str + t: bool + s: int | str + + +class CompactBrowserEntry(TypedDict, total=False): + d: list[CompactFolder] + f: list[CompactFile] + + +def decode_search_payload(data: object) -> list[dict[str, object]]: + if not isinstance(data, dict): + return [] + compact = cast(CompactCorpus, data) + repos = compact.get("rp", []) or [] + folders = compact.get("fd", []) or [] + records: list[dict[str, object]] = [] + for raw_item in compact.get("rc", []) or []: + if not isinstance(raw_item, list): + continue + item = cast(list[object], raw_item) + if len(item) < 6: + continue + repo = repos[item[0]] if isinstance(item[0], int) and 0 <= item[0] < len(repos) else "" + folder = folders[item[3]] if isinstance(item[3], int) and 0 <= item[3] < len(folders) else [] + records.append({ + "Repo": repo, + "File": item[1], + "Extension": item[2], + "Folder": folder, + "Size": item[4], + "HasTxt": bool(item[5]), + }) + return records + + +def decode_tree_node(node: CompactTreeNode, parent_path: str = "", is_root: bool = False) -> dict[str, object]: + name = node.get("n", "") + path = "" if is_root else (f"{parent_path}/{name}" if parent_path else name) + children = [decode_tree_node(child, path, False) for child in node.get("ch", [])] + decoded: dict[str, object] = { + "name": name, + "path": path, + "count": node.get("c", 0), + "hasDirectFiles": node.get("df", False), + "hasChildren": len(children) > 0, + "showSelfToggle": bool(path and node.get("df", False) and len(children) > 0), + "children": children, + } + if is_root: + decoded["isRoot"] = True + return decoded + + +def decode_folder_tree_data(data: dict[str, list[CompactTreeNode]] | None) -> dict[str, list[dict[str, object]]]: + return {repo: [decode_tree_node(node, "", True) for node in nodes] + for repo, nodes in (data or {}).items()} + + +def decode_browser_entry(entry: CompactBrowserEntry, current_path: str = "") -> dict[str, object]: + return { + "folders": [ + { + "name": item.get("n", ""), + "path": f"{current_path}/{item.get('n', '')}" if current_path else item.get("n", ""), + "count": item.get("c", 0), + } + for item in entry.get("d", []) + ], + "files": [ + { + "name": item.get("n", ""), + "ext": item.get("e", ""), + "hasTxt": item.get("t", False), + "size": item.get("s", ""), + } + for item in entry.get("f", []) + ], + "current_path": current_path, + } + + +def decode_folder_browser_data(data: dict[str, dict[str, CompactBrowserEntry]] | None) -> dict[str, dict[str, dict[str, object]]]: + return {repo: {path: decode_browser_entry(entry, path) for path, entry in (browser or {}).items()} + for repo, browser in (data or {}).items()} diff --git a/backend/search/corpus/domain/records.py b/backend/search/corpus/domain/records.py new file mode 100644 index 0000000000000000000000000000000000000000..67542a8c94a04e658119fcb5ad8927a392d12c87 --- /dev/null +++ b/backend/search/corpus/domain/records.py @@ -0,0 +1,185 @@ +"""Pure record paths and reader projections shared by search and reader APIs.""" +import posixpath +import re +from typing import cast +from urllib.parse import quote + + +READER_ASSET_MODES = { + "p": "pdf", "e": "epub", "d": "docx", "h": "html", + "t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video", "f": "swf", +} +READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"}) + + +def build_record_relative_path(rec: dict[str, object]) -> str: + file_name = cast(str, rec.get("File", "")) + extension = cast(str, rec.get("Extension", "")) + full_name = f"{file_name}.{extension}" if extension else file_name + folders = cast(list[str], rec.get("Folder", []) or []) + return posixpath.join(*folders, full_name) if folders else full_name + + +def build_reader_asset_key(rec: dict[str, object]) -> str: + return f"{rec.get('Repo', '')}\0{build_record_relative_path(rec)}" + + +def dataset_file_url(repo: str, relative_path: str, action: str = "resolve") -> str: + return f"https://huggingface.co/datasets/{repo}/{action}/main/{quote(relative_path, safe='/')}" + + +def dataset_file_urls(repo: str, relative_path: str) -> tuple[str, str]: + """Produce source and browser URLs using the same encoded path.""" + encoded = quote(relative_path, safe="/") + prefix = f"https://huggingface.co/datasets/{repo}" + return f"{prefix}/resolve/main/{encoded}", f"{prefix}/blob/main/{encoded}" + + +def build_record_link(rec: dict[str, object]) -> str: + return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec)) + + +def build_record_path_url(rec: dict[str, object]) -> str: + return dataset_file_url(cast(str, rec.get("Repo", "")), build_record_relative_path(rec), "blob") + + +def build_browser_file_name(file_item: dict[str, object]) -> str: + name = str(file_item.get("name", "") or "file") + ext = str(file_item.get("ext", "") or "") + # Browser metadata stores the source record's stem and last extension in + # separate fields; a repeated suffix in the stem is still significant. + if not ext: + return name + return f"{name}.{ext}" + + +def enrich_browser_entry(repo: str, path: str, entry: dict[str, object]) -> dict[str, object]: + decoded = dict(entry or {}) + decoded["current_path"] = decoded.get("current_path", path) + folders: list[dict[str, object]] = [] + for folder in cast(list[dict[str, object]], decoded.get("folders", []) or []): + item = dict(folder) + if "path" not in item: + name = item.get("name", "") + item["path"] = f"{path}/{name}" if path else name + folders.append(item) + files: list[dict[str, object]] = [] + for file_item in cast(list[dict[str, object]], decoded.get("files", []) or []): + item = dict(file_item) + full_name = build_browser_file_name(item) + rel_path = f"{path}/{full_name}" if path else full_name + if not item.get("link") and not item.get("path"): + item["link"], item["path"] = dataset_file_urls(repo, rel_path) + else: + item["link"] = item.get("link") or dataset_file_url(repo, rel_path) + item["path"] = item.get("path") or dataset_file_url(repo, rel_path, "blob") + files.append(item) + decoded["folders"] = folders + decoded["files"] = files + return decoded + + +def reader_asset_url(asset: dict[str, object]) -> str: + path = quote(str(asset.get("p") or ""), safe="/") + return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + path + + +def reader_extension_for_asset(asset: dict[str, object], original_extension: str = "") -> str: + asset_path = str(asset.get("p") or "") + if asset.get('c'): + return 'epub-chapters' + if asset_path.endswith(("page-manifest.json", "reading-manifest.json")): + return "image-pages" if asset.get("m") == "i" else "pdf-pages" + if asset.get("m") == "e": + match = re.search(r"/(?:document|book)\.(epub|mobi|azw|azw3|fb2)$", asset_path, re.IGNORECASE) + if match: + return match.group(1).lower() + extension = str(original_extension or "").lower().lstrip(".") + return extension if extension in READER_NATIVE_FOLIATE_EXTENSIONS else "epub" + mode = asset.get("m") + return READER_ASSET_MODES.get(mode, "") if isinstance(mode, str) else "" + + +def _reader_bucket_url(path: str) -> str: + return "https://voiceofml-search.hf.space/api/reader-bucket-resource?path=" + quote(path, safe="/") + + +def reader_asset_fields(asset: dict[str, object], original_extension: str) -> dict[str, str]: + ocr_path = str(asset.get("o") or "") + ocr_bucket = asset.get("b") == "vomebook/pdf-pages-v2" or asset.get("ob") == "vomebook/pdf-pages-v2" + fields: dict[str, str] = {} + if ocr_path.endswith("/ocr-manifest.json") and ocr_bucket: + fields["ocr_manifest"] = _reader_bucket_url(ocr_path) + fields["ocr_mode"] = str(asset.get("om") or "") + if asset.get("s") == 3: + return fields + if asset.get("s") != 2 or asset.get("m") not in READER_ASSET_MODES or not asset.get("p"): + return fields + if str(original_extension).lower().lstrip('.') == 'djvu': + # Existing OCR remains independent. Native DjVu reading starts at the + # dataset source, never an older image stream, manifest or derivative. + return fields + if (asset.get('m') == 'p' and not asset.get('c') and str(asset['p']).endswith('/page-manifest.json') + and str(original_extension).lower().lstrip('.') != 'djvu'): + # Legacy page indexes no longer own PDF/converted-PDF reading. Keep + # independent OCR metadata and prefer the validated PDF companion. + if asset.get('pd') and asset.get('pdb') in {'vomebook/reader-assets-v2', 'vomebook/pdf-pages-v2'}: + fields.update(url=_reader_bucket_url(cast(str, asset['pd'])), extension='pdf') + return fields + fields.update({"url": reader_asset_url(asset), "extension": reader_extension_for_asset(asset, original_extension)}) + if asset.get("pd") and asset.get("pdb") in {"vomebook/reader-assets-v2", "vomebook/pdf-pages-v2"}: + fields["pdf_document"] = _reader_bucket_url(cast(str, asset["pd"])) + if asset.get("c"): + if asset.get("cb") == "vomebook/reader-assets-v2": + fields["chapter_manifest"] = _reader_bucket_url(cast(str, asset["c"])) + elif asset.get("cb") == "vomebook/pdf-pages-v2": + fields["chapter_manifest"] = "/api/reader-bucket-resource?path=" + quote(cast(str, asset["c"]), safe="/") + return fields + + +def enrich_reader_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]: + result = dict(record) + fields = reader_asset_fields(asset, cast(str, record.get("Extension", ""))) + direct_modes = { + "pdf": ("pdf", "pdf"), "djvu": ("djvu", "pdf"), "vcf": ("vcf", "text"), "ini": ("ini", "text"), + "tif": ("image", "image"), "tiff": ("image", "image"), + } + direct_extension = str(record.get("Extension") or "").lower().lstrip(".") + if 'url' not in fields and direct_extension in direct_modes: + # A PDF without a converted/page asset remains directly readable from + # its immutable source dataset after the derived asset store changes. + fields.update(url=cast(str, record.get("Link") or build_record_link(record)), + extension=direct_modes[direct_extension][0]) + if fields: + for source, target in (("url", "ReaderLink"), ("extension", "ReaderExtension"), + ("chapter_manifest", "ReaderChapterManifest"), + ("ocr_manifest", "ReaderOcrManifest"), ("ocr_mode", "ReaderOcrMode"), + ("pdf_document", "ReaderPdfDocument")): + if source in fields: + result[target] = fields[source] + result["DownloadLink"] = record.get("Link") or build_record_link(record) + return result + + +def add_reader_assets(payload: dict[str, object], assets: dict[str, object]) -> dict[str, object]: + files = cast(dict[str, dict[str, object]], assets.get("f", {})) + return {**payload, "results": [ + enrich_reader_record(record, files.get(build_reader_asset_key(record), {})) + for record in cast(list[dict[str, object]], payload.get("results", [])) + ]} + + +def reader_resolved_record(record: dict[str, object], asset: dict[str, object]) -> dict[str, object]: + source = record.get("Link") or build_record_link(record) + extension = str(record.get("Extension") or "").lower().lstrip(".") + repo = cast(str, record.get("Repo", "")).split("/")[-1] + folders = [str(item) for item in cast(list[object], record.get("Folder", []))] + return { + "url": source, "download": source, "extension": extension, + "original_extension": extension, "title": record.get("File") or record.get("Name") or "在线阅读", + # Keep the exact indexed filename separate from the display title. + # The stem may itself end in an extension, or include trailing spaces. + "filename": build_record_relative_path(record).rsplit("/", 1)[-1], + "path": "/".join([repo, *folders]), "folder": "/".join(folders), "repo": repo, + **reader_asset_fields(asset, extension), + } diff --git a/backend/search/corpus/domain/words.py b/backend/search/corpus/domain/words.py new file mode 100644 index 0000000000000000000000000000000000000000..8b3ebd3c3aa19a90e22be472e9064d7c36faf23f --- /dev/null +++ b/backend/search/corpus/domain/words.py @@ -0,0 +1,65 @@ +"""Pure search token matching and word-index construction.""" +from collections.abc import Callable, Iterable, Mapping, Sequence +import hashlib +import re +from typing import cast + + +def records_digest(records: Sequence[Mapping[str, object]]) -> bytes: + digest = hashlib.sha256() + for record in records: + for value in (record.get("_file_lower", ""), record.get("_repo_lower", ""), + record.get("_folder_path_lower", "")): + digest.update(cast(str, value).encode("utf-8")) + digest.update(b"\0") + return digest.digest() + + +def tokenize(text: str, segment: Callable[[str], list[str]]) -> list[str]: + tokens: list[str] = [] + text_lower = text.lower() + tokens.extend(re.findall(r"[a-z0-9]+", text_lower)) + chinese_text = re.sub(r"[a-z0-9\s]+", " ", text_lower) + chinese_text = re.sub(r"[^\u4e00-\u9fff\u3400-\u4dbf\s]+", " ", chinese_text) + chinese_tokens = segment(chinese_text) + tokens.extend([token.strip() for token in chinese_tokens if token.strip()]) + chinese_token_set = set(chinese_tokens) + for ch in text_lower: + if "\u4e00" <= ch <= "\u9fff" or "\u3400" <= ch <= "\u4dbf": + if ch not in chinese_token_set: + tokens.append(ch) + # Stable token order keeps rebuilt vocabularies reproducible across hash seeds. + return list(dict.fromkeys(tokens)) + + +def matches_file_token(record: Mapping[str, object], token: str) -> bool: + return (token in cast(str, record.get("_full_file_lower", record.get("_file_lower", ""))) + or token in cast(str, record.get("_repo_lower", ""))) + + +def matches_file_query(record: Mapping[str, object], tokens: Iterable[str], fuzzy_tokens: set[str], *, + tokenize_text: Callable[[str], list[str]], + file_match: Callable[[Mapping[str, object], str], bool], + fuzzy_match: Callable[[str, str], bool]) -> bool: + file_tokens = tokenize_text(cast(str, record.get("_full_file_lower", record.get("_file_lower", "")))) if fuzzy_tokens else [] + return all(file_match(record, token) or ( + token in fuzzy_tokens and any(fuzzy_match(token, word) for word in file_tokens) + ) for token in tokens) + + +def build_vocab_by_len(words: Iterable[str], vocab: dict[int, list[str]]) -> None: + for word in words: + vocab.setdefault(len(word), []).append(word) + # Generated postings are sorted by term; rebuilt indexes must traverse the + # same vocabulary regardless of insertion order or Python hash seed. + for bucket in vocab.values(): + bucket.sort() + + +def build_word_index(records: Sequence[Mapping[str, object]], index: dict[str, set[int]], + tokenize_text: Callable[[str], list[str]]) -> None: + for idx, record in enumerate(records): + file_name = cast(str, record.get("File", "")) + folders = cast(list[str], record.get("Folder", [])) + for token in tokenize_text(" ".join([file_name] + folders)): + index.setdefault(token, set()).add(idx) diff --git a/backend/search/corpus/infrastructure/__init__.py b/backend/search/corpus/infrastructure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7a95652886ff6659874e41b75772b9df59ec9b5 --- /dev/null +++ b/backend/search/corpus/infrastructure/__init__.py @@ -0,0 +1 @@ +"""search corpus infrastructure package.""" diff --git a/backend/search/corpus/infrastructure/indexes.py b/backend/search/corpus/infrastructure/indexes.py new file mode 100644 index 0000000000000000000000000000000000000000..84c3492e3370b565d648d89044a951862594c4e4 --- /dev/null +++ b/backend/search/corpus/infrastructure/indexes.py @@ -0,0 +1,205 @@ +"""Readers for the generated word and n-gram posting files. + +The generated formats are deliberately small and self-describing. Keeping +their parsing independent from the FastAPI application makes malformed input +handling testable without importing application state. +""" + +import gzip +from collections.abc import Iterator +from pathlib import Path +from typing import Literal, overload + +try: + import _search_index_native as _native_index +except ImportError: + _native_index = None + +_native_read_entries = getattr(_native_index, "read_entries", None) +_native_decode_postings = getattr(_native_index, "decode_postings", None) + + +NGRAM_MAGIC = b"VNG3" +WORD_INDEX_MAGIC = b"VWI2" +WORD_INDEX_TOKENIZER = "jieba-0.42.1-cjk-char-v1" + +PostingLocation = tuple[int, int, int] +Posting = set[int] | PostingLocation +PostingIndex = dict[str, Posting] + + +def decode_varint(data: bytes, offset: int) -> tuple[int, int]: + value = 0 + shift = 0 + while offset < len(data): + byte = data[offset] + offset += 1 + value |= (byte & 0x7F) << shift + if not byte & 0x80: + return value, offset + shift += 7 + raise ValueError("truncated varint") + + +def decode_postings(data: bytes | memoryview, record_count: int | None = None) -> set[int]: + # Non-byte, strided, or mutable-backed buffers retain Python iteration semantics. + if (_native_decode_postings is not None and record_count is None and + (type(data) is bytes or (type(data) is memoryview and data.readonly and + type(data.obj) is bytes and data.format == "B" and + data.ndim == 1 and data.c_contiguous))): + try: + return _native_decode_postings(data) + except OverflowError: + # Python integers support valid varints and cumulative IDs wider than 64 bits. + pass + return _decode_postings_python(data, record_count) + + +def _decode_postings_python(data: bytes | memoryview, record_count: int | None = None) -> set[int]: + record_ids: set[int] = set() + previous = 0 + value = shift = 0 + for byte in data: + value |= (byte & 0x7F) << shift + if byte & 0x80: + shift += 7 + continue + previous += value + if record_count is not None and previous >= record_count: + raise ValueError("posting record id out of range") + record_ids.add(previous) + value = shift = 0 + if shift: + raise ValueError("truncated varint") + return record_ids + + +def _bounded_slice(data: bytes, offset: int, length: int) -> tuple[int, int]: + end = offset + length + if length < 0 or end < offset or end > len(data): + raise ValueError("truncated postings") + return offset, end + + +def _validate_postings(data: bytes, start: int, end: int, record_count: int) -> int: + """Count distinct monotonic IDs without allocating a temporary posting set.""" + previous = 0 + last = -1 + count = 0 + value = shift = 0 + for offset in range(start, end): + byte = data[offset] + value |= (byte & 0x7F) << shift + if byte & 0x80: + shift += 7 + continue + previous += value + if previous >= record_count: + raise ValueError("posting record id out of range") + if previous != last: + count += 1 + last = previous + value = shift = 0 + if shift: + raise ValueError("truncated varint") + return count + + +def _read_posting_entries(data: bytes, offset: int, count: int, record_count: int, + materialize: bool = True) -> Iterator[tuple[str, PostingLocation, set[int] | None]]: + """Yield validated entries while leaving storage policy to each loader.""" + for _ in range(count): + key_length, offset = decode_varint(data, offset) + key_start, offset = _bounded_slice(data, offset, key_length) + key = data[key_start:offset].decode("utf-8") + posting_count, offset = decode_varint(data, offset) + posting_length, offset = decode_varint(data, offset) + posting_start, offset = _bounded_slice(data, offset, posting_length) + decoded = decode_postings(memoryview(data)[posting_start:offset], record_count) if materialize else None + actual_count = len(decoded) if decoded is not None else _validate_postings(data, posting_start, offset, record_count) + if actual_count != posting_count: + raise ValueError("posting count mismatch") + yield key, (posting_start, offset, posting_count), decoded + if offset != len(data): + raise ValueError("trailing postings") + + +def _load_posting_entries(data: bytes, offset: int, count: int, record_count: int, + materialize: bool) -> PostingIndex: + if _native_read_entries is not None: + try: + return _native_read_entries(data, offset, count, record_count, materialize) + except OverflowError: + # Retain arbitrary-width varint behavior for unusual valid inputs. + pass + if materialize: + entries: PostingIndex = {} + for key, _, decoded in _read_posting_entries(data, offset, count, record_count, True): + if decoded is None: + raise RuntimeError("materialized posting missing") + entries[key] = decoded + return entries + return {key: location for key, location, _ in _read_posting_entries(data, offset, count, record_count, False)} + + +def load_ngram_index( + path: Path, + width: int, + record_count: int, + expected_digest: bytes, +) -> tuple[PostingIndex, bytes]: + try: + data = gzip.decompress(path.read_bytes()) + if not data.startswith(NGRAM_MAGIC) or len(data) < 37 or data[4] != width: + return {}, b"" + if data[5:37] != expected_digest: + return {}, b"" + offset = 37 + stored_record_count, offset = decode_varint(data, offset) + count, offset = decode_varint(data, offset) + if stored_record_count != record_count: + return {}, b"" + postings = _load_posting_entries(data, offset, count, record_count, False) + return postings, data + except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError): + return {}, b"" + + +@overload +def load_word_index(path: Path, record_count: int, expected_digest: bytes, + materialize: Literal[False]) -> tuple[PostingIndex, bytes]: ... + + +@overload +def load_word_index(path: Path, record_count: int, expected_digest: bytes, + materialize: Literal[True] = True) -> PostingIndex: ... + + +def load_word_index(path: Path, record_count: int, expected_digest: bytes, + materialize: bool = True) -> PostingIndex | tuple[PostingIndex, bytes]: + try: + data = gzip.decompress(path.read_bytes()) + if not data.startswith(WORD_INDEX_MAGIC): + return {} if materialize else ({}, b"") + offset = len(WORD_INDEX_MAGIC) + tokenizer_length, offset = decode_varint(data, offset) + tokenizer_start, offset = _bounded_slice(data, offset, tokenizer_length) + tokenizer = data[tokenizer_start:offset].decode("utf-8") + digest_start, offset = _bounded_slice(data, offset, 32) + if tokenizer != WORD_INDEX_TOKENIZER or data[digest_start:offset] != expected_digest: + return {} if materialize else ({}, b"") + stored_record_count, offset = decode_varint(data, offset) + count, offset = decode_varint(data, offset) + if stored_record_count != record_count: + return {} if materialize else ({}, b"") + entries = _load_posting_entries(data, offset, count, record_count, materialize) + return entries if materialize else (entries, data) + except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError): + return {} if materialize else ({}, b"") + + +def resolve_postings(value: Posting | frozenset[int] | bytes | memoryview, buffer: bytes) -> set[int]: + if isinstance(value, tuple): + start, end, _ = value + return decode_postings(memoryview(buffer)[start:end]) + return set(value) if isinstance(value, (set, frozenset)) else decode_postings(value) diff --git a/backend/search/corpus/infrastructure/selection.py b/backend/search/corpus/infrastructure/selection.py new file mode 100644 index 0000000000000000000000000000000000000000..ee6b436043fca92e2b248cf35eddbbeef7c09f32 --- /dev/null +++ b/backend/search/corpus/infrastructure/selection.py @@ -0,0 +1,290 @@ +"""Select a verified, immutable local search-data generation before startup. + +The caller supplies the build-materialized directory. Selection is opt-in and +all-or-nothing: hashes, lengths, path containment and gzip/JSON structure are +checked before any application paths are changed. This module never writes a +bucket pointer or downloads data and does not replace a running process's data. +""" +from __future__ import annotations + +import gzip +import hashlib +import json +import re +from dataclasses import dataclass +from pathlib import Path +from typing import cast +from urllib.parse import quote + +from backend.search.corpus.infrastructure.indexes import load_ngram_index, load_word_index + + +SHA = re.compile(r"[0-9a-f]{64}\Z") +MANDATORY = frozenset({"search_data.json.gz", "folder_tree.json.gz", "folder_browser.json.gz", + "search_words.bin.gz", "search_ngrams_2.bin.gz", "search_ngrams_3.bin.gz", + "initial/global.json", "initial/manifest.json", "sidebar/global.json", "sidebar/manifest.json"}) +MAX_FILE = 32 * 1024 * 1024 +MAX_EXPANDED = 256 * 1024 * 1024 +MAX_FILES = 1024 + + +def as_mapping(value: object, label: str) -> dict[str, object]: + if not isinstance(value, dict): + raise ValueError(f"{label} must be an object") + mapping = cast(dict[object, object], value) + if any(not isinstance(key, str) for key in mapping): + raise ValueError(f"{label} keys must be strings") + return cast(dict[str, object], mapping) + + +def as_list(value: object, label: str) -> list[object]: + if not isinstance(value, list): + raise ValueError(f"{label} must be an array") + return cast(list[object], value) + + +def canonical(value: object) -> bytes: + return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), + allow_nan=False) + "\n").encode("utf-8") + + +def read_compressed_mapping(path: Path, label: str) -> dict[str, object]: + """Bound expanded generated JSON before interpreting any directory data.""" + try: + with gzip.open(path, "rb") as stream: + raw = stream.read(MAX_EXPANDED + 1) + except (OSError, EOFError) as error: + raise ValueError(f"invalid compressed {label}") from error + if len(raw) > MAX_EXPANDED: + raise ValueError(f"expanded {label} exceeds limit") + try: + return as_mapping(json.loads(raw), label) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise ValueError(f"invalid {label} JSON") from error + + +def read_json_mapping(path: Path, label: str) -> dict[str, object]: + try: + return as_mapping(json.loads(path.read_bytes()), label) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise ValueError(f"invalid {label} JSON") from error + + +def append_bootstrap_record(global_prefix: list[dict[str, object]], repo_prefix: list[dict[str, object]], + record: dict[str, object]) -> None: + """Keep bounded prefixes; avoid retaining every decoded corpus record.""" + if len(global_prefix) < 500: + global_prefix.append(record) + if len(repo_prefix) < 500: + repo_prefix.append(record) + + +def validate_directory_data(root: Path, repos: list[str]) -> dict[str, dict[str, object]]: + tree = read_compressed_mapping(root / "folder_tree.json.gz", "Space folder tree") + browser = read_compressed_mapping(root / "folder_browser.json.gz", "Space folder browser") + if set(tree) != set(repos) or set(browser) != set(repos): + raise ValueError("Space directory repositories mismatch") + roots: dict[str, dict[str, object]] = {} + for repo in repos: + nodes = as_list(tree[repo], "Space folder roots") + pending = list(nodes) + while pending: + node = as_mapping(pending.pop(), "Space folder node") + if not isinstance(node.get("n"), str) or type(node.get("c")) is not int or cast(int, node["c"]) < 0: + raise ValueError("invalid Space folder node") + if not isinstance(node.get("df"), bool): + raise ValueError("invalid Space folder node") + pending.extend(as_list(node.get("ch"), "Space folder children")) + paths = as_mapping(browser[repo], "Space folder browser paths") + if "" not in paths: + raise ValueError("Space folder browser root missing") + for path, value in paths.items(): + entry = as_mapping(value, "Space folder browser entry") + for folder in as_list(entry.get("d"), "Space folder browser folders"): + item = as_mapping(folder, "Space folder browser folder") + if not isinstance(item.get("n"), str) or type(item.get("c")) is not int or cast(int, item["c"]) < 0: + raise ValueError("invalid Space folder browser folder") + for file in as_list(entry.get("f"), "Space folder browser files"): + item = as_mapping(file, "Space folder browser file") + if (not isinstance(item.get("n"), str) or not isinstance(item.get("e"), str) + or not isinstance(item.get("t"), bool) + or not isinstance(item.get("s"), (int, str)) or isinstance(item.get("s"), bool)): + raise ValueError("invalid Space folder browser file") + if path == "": + roots[repo] = entry + return roots + + +def safe_name(name: object) -> bool: + if (not isinstance(name, str) or not name or name.startswith("/") or "\\" in name + or any(part in {"", ".", ".."} for part in name.split("/")) + or any(ord(char) < 32 or ord(char) == 127 for char in name)): + return False + return name in MANDATORY or bool(re.fullmatch(r"(?:initial|sidebar)/repos/[^/]+\.json", name)) + + +@dataclass(frozen=True) +class SelectedGeneration: + generation: str + directory: Path + file_count: int + record_count: int + + +def inspect_generation(directory: Path, generation: str) -> SelectedGeneration: + """Verify every advertised Space member and return the immutable selection.""" + if not SHA.fullmatch(generation): + raise ValueError("invalid search generation identity") + if directory.is_symlink() or not directory.is_dir(): + raise ValueError("generation directory must be an ordinary directory") + root = directory.resolve() + report_file = root / "generation-manifest.json" + if report_file.is_symlink() or not report_file.is_file() or report_file.stat().st_size > 1024 * 1024: + raise ValueError("missing or oversized local generation manifest") + raw_manifest = report_file.read_bytes() + manifest = as_mapping(json.loads(raw_manifest), "search generation manifest") + if (manifest.get("version") != 1 or manifest.get("kind") != "search-snapshot-local" + or manifest.get("generation") != generation + or manifest.get("object_layout") != "objects/sha256//"): + raise ValueError("invalid search generation manifest") + excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"} + identity = {key: value for key, value in manifest.items() if key not in excluded} + if hashlib.sha256(canonical(identity)).hexdigest() != generation: + raise ValueError("search manifest identity mismatch") + objects = as_mapping(manifest.get("objects"), "generation objects") + files = as_mapping(manifest.get("files"), "generation files") + entries = as_mapping(objects.get("space"), "Space objects") + original = as_mapping(files.get("space"), "Space files") + if set(entries) != set(original): + raise ValueError("Space manifest member mismatch") + actual: set[str] = set() + for path in root.rglob("*"): + if path.is_symlink(): + raise ValueError("symlinks are forbidden in generation files") + if path.is_file() and path != report_file: + actual.add(path.relative_to(root).as_posix()) + elif not path.is_dir() and path != report_file: + raise ValueError("generation contains a non-file object") + if actual != set(entries): + raise ValueError("Space generation contains missing or unlisted files") + if not MANDATORY <= set(entries) or len(entries) > MAX_FILES: + raise ValueError("Space generation is incomplete") + for name, item in entries.items(): + if not safe_name(name): + raise ValueError("invalid Space member") + metadata = as_mapping(item, "Space member metadata") + original_metadata = as_mapping(original[name], "original Space member metadata") + digest, size = metadata.get("sha256"), metadata.get("bytes") + if (not isinstance(digest, str) or not SHA.fullmatch(digest) or type(size) is not int + or not 1 <= size <= MAX_FILE or original_metadata != {"sha256": digest, "bytes": size} + or metadata.get("object") != f"objects/sha256/{digest[:2]}/{digest}"): + raise ValueError("Space member identity mismatch") + path = root.joinpath(*name.split("/")) + if not path.is_file() or root not in path.resolve().parents or path.stat().st_size != size: + raise ValueError("Space member missing or wrong size") + if hashlib.sha256(path.read_bytes()).hexdigest() != digest: + raise ValueError("Space member digest mismatch") + corpus_path = root / "search_data.json.gz" + with gzip.open(corpus_path, "rb") as stream: + decoded = stream.read(MAX_EXPANDED + 1) + if len(decoded) > MAX_EXPANDED: + raise ValueError("expanded search corpus exceeds limit") + corpus = as_mapping(json.loads(decoded), "Space corpus") + rows = as_list(corpus.get("rc"), "Space corpus records") + if corpus.get("v") != 2 or len(rows) != manifest.get("record_count") or not rows: + raise ValueError("Space corpus record count mismatch") + # Index files are not allowed to silently degrade into an empty/rebuilt + # index when the selected generation is loaded by the actual application. + repos = as_list(corpus.get("rp"), "Space corpus repositories") + folders = as_list(corpus.get("fd"), "Space corpus folders") + if (not repos or any(not isinstance(repo, str) or not re.fullmatch(r"VoiceOfML/[A-Za-z0-9._-]+", repo) + for repo in repos)): + raise ValueError("invalid Space corpus repository dictionary") + repo_names = cast(list[str], repos) + if len(set(repo_names)) != len(repo_names) or len({repo.split("/")[-1] for repo in repo_names}) != len(repo_names): + raise ValueError("duplicate Space corpus repository") + folder_names: list[list[str]] = [] + for value in folders: + folder = as_list(value, "Space corpus folder") + if any(not isinstance(part, str) for part in folder): + raise ValueError("invalid Space corpus folder") + folder_names.append(cast(list[str], folder)) + digest_builder = hashlib.sha256() + # Bootstrap pages contain at most 500 rows; retain only those prefixes and + # counts rather than materializing another complete Python corpus. + repo_prefixes: dict[str, list[dict[str, object]]] = {repo: [] for repo in repo_names} + repo_counts = dict.fromkeys(repo_names, 0) + global_prefix: list[dict[str, object]] = [] + for row in rows: + item = as_list(row, "Space corpus record") + if (len(item) != 6 or type(item[0]) is not int or not 0 <= item[0] < len(repo_names) + or not isinstance(item[1], str) or not isinstance(item[2], str) or type(item[3]) is not int + or not 0 <= item[3] < len(folder_names) or type(item[5]) is not int or item[5] not in (0, 1)): + raise ValueError("invalid Space corpus record") + if not isinstance(item[4], (int, str)) or isinstance(item[4], bool): + raise ValueError("invalid Space corpus record size") + repo = repo_names[item[0]] + repo_counts[repo] += 1 + if len(global_prefix) < 500 or len(repo_prefixes[repo]) < 500: + record: dict[str, object] = {"Repo": repo, "File": item[1], "Extension": item[2], + "Folder": folder_names[item[3]], "Size": item[4], "HasTxt": bool(item[5])} + append_bootstrap_record(global_prefix, repo_prefixes[repo], record) + for text in (item[1], repo_names[item[0]], "/".join(folder_names[item[3]])): + digest_builder.update(text.lower().encode("utf-8")) + digest_builder.update(b"\0") + browser_roots = validate_directory_data(root, repo_names) + digest = digest_builder.digest() + words, _ = load_word_index(root / "search_words.bin.gz", len(rows), digest, materialize=False) + if not words: + raise ValueError("Space word index is missing, invalid or empty") + for width in (2, 3): + grams, _ = load_ngram_index(root / f"search_ngrams_{width}.bin.gz", width, len(rows), digest) + if not grams: + raise ValueError(f"Space {width}-gram index is missing, invalid or empty") + for family in ("initial", "sidebar"): + listing = read_json_mapping(root / family / "manifest.json", "Space bootstrap manifest") + urls = as_list(listing.get("urls"), "Space bootstrap URLs") + if not urls: + raise ValueError("invalid Space bootstrap manifest") + prefix = f"/data/{family}/" + listed: set[str] = set() + for url in urls: + if not isinstance(url, str) or not url.startswith(prefix): + raise ValueError("invalid Space bootstrap URL") + name = f"{family}/" + url[len(prefix):] + if not safe_name(name) or name not in entries or name in listed or name.endswith("/manifest.json"): + raise ValueError("missing or duplicated Space bootstrap member") + listed.add(name) + expected = {name for name in entries if name == f"{family}/global.json" + or name.startswith(f"{family}/repos/")} + wanted = {f"{family}/global.json"} | { + f"{family}/repos/{quote(repo.split('/')[-1], safe='')}.json" for repo in repo_names} + if listed != expected or listed != wanted: + raise ValueError("Space bootstrap manifest does not cover its members") + for repo in [None, *repo_names]: + name = "initial/global.json" if repo is None else f"initial/repos/{quote(repo.split('/')[-1], safe='')}.json" + payload = read_json_mapping(root / name, "Space initial payload") + expected_records = global_prefix if repo is None else repo_prefixes[repo] + expected_total = len(rows) if repo is None else repo_counts[repo] + page_size = payload.get("page_size") + if (payload.get("version") != 2 or payload.get("mode") != ("global" if repo is None else "repo") + or payload.get("repo") != repo or payload.get("sort") != "relevance" or payload.get("page") != 1 + or type(page_size) is not int or not 1 <= page_size <= 500 + or payload.get("total") != expected_total + or payload.get("results") != expected_records[:page_size]): + raise ValueError("Space initial payload does not match corpus") + sidebar = read_json_mapping(root / "sidebar/global.json", "Space sidebar payload") + repo_summaries = as_list(sidebar.get("repos"), "Space sidebar repositories") + expected_summaries = [{"name": repo, "count": repo_counts[repo]} for repo in sorted(repo_names)] + if repo_summaries != expected_summaries: + raise ValueError("Space sidebar repositories do not match corpus") + for repo in repo_names: + name = f"sidebar/repos/{quote(repo.split('/')[-1], safe='')}.json" + payload = read_json_mapping(root / name, "Space sidebar repository") + root_entry = browser_roots[repo] + if (payload.get("repo") != repo or payload.get("path") != "" + or payload.get("folders") != root_entry.get("d") + or payload.get("files") != root_entry.get("f")): + raise ValueError("invalid Space sidebar repository") + return SelectedGeneration(generation=generation, directory=root, file_count=len(entries), + record_count=len(rows)) diff --git a/backend/search/domain/browse.py b/backend/search/domain/browse.py new file mode 100644 index 0000000000000000000000000000000000000000..ddcdb253963172ce94026e9b041cd8b681b361b9 --- /dev/null +++ b/backend/search/domain/browse.py @@ -0,0 +1,47 @@ +"""Plan empty-query browsing against caller-owned search indexes.""" +from __future__ import annotations + +from collections.abc import Callable, Sequence + +Size = int | float | None +Paths = Sequence[str] | None +RecordFilter = Callable[[Sequence[int], Paths, Paths, Paths, Size, Size, str], list[int]] +MixedRecordFilter = Callable[[Sequence[int], Paths, Paths, Size, Size], list[int]] +MixedFilter = Callable[[Sequence[int], Paths, Paths], Sequence[int]] +MixedCandidates = Callable[[Paths, Paths, Paths], list[int] | None] + + +def browse_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size, + folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths, sort: str, *, + get_precomputed: Callable[[Paths, str], Sequence[int]], + get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]], + filter_mixed: MixedFilter, filter_records: RecordFilter, + filter_mixed_records: MixedRecordFilter, key_name: Callable[[int], str], key_size: Callable[[int], tuple[int | float, str]]) -> Sequence[int]: + """Preserve precomputed order identity or filter a bounded corpus snapshot.""" + has_filters = (extensions or folders or min_size is not None or max_size is not None + or folder_match_mode == "mixed") + if not has_filters and (not repos or len(repos) == 1): + return get_precomputed(repos, sort) + filtered = _filtered_order(repos, extensions, folders, min_size, max_size, folder_match_mode, + folder_selfs, folder_subtrees, get_mixed_candidates, get_initial, + filter_mixed, filter_records, filter_mixed_records) + if sort == "name": + filtered.sort(key=key_name) + elif sort == "size": + filtered.sort(key=key_size) + return filtered + + +def _filtered_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size, + folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths, + get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]], + filter_mixed: MixedFilter, filter_records: RecordFilter, + filter_mixed_records: MixedRecordFilter) -> list[int]: + if folder_match_mode == "mixed": + indices = get_mixed_candidates(repos, folder_selfs, folder_subtrees) + if indices is None: + indices = get_initial(repos) + mixed = filter_mixed(indices, folder_selfs, folder_subtrees) + return filter_mixed_records(mixed, repos, extensions, min_size, max_size) + indices = get_initial(repos) + return filter_records(indices, repos, extensions, folders, min_size, max_size, folder_match_mode) diff --git a/backend/search/domain/candidates.py b/backend/search/domain/candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..805091f98059b38b815dbad7062432780d64768b --- /dev/null +++ b/backend/search/domain/candidates.py @@ -0,0 +1,72 @@ +"""Typed literal n-gram candidate selection over caller-owned search state.""" +from __future__ import annotations + +from collections.abc import Callable, Iterable, Mapping, Sequence +import re +from backend.search.corpus.infrastructure.indexes import Posting, PostingIndex + +PostingResolver = Callable[[Posting, bytes], set[int]] + + +def wildcard_literal_candidates(query: str, repos: Iterable[str] | None, + get_candidates: Callable[[str, Iterable[str] | None], set[int] | None], + get_scope: Callable[[Iterable[str] | None], Sequence[int]]) -> list[int]: + """Bound wildcard search by a safe mandatory CJK, digit or ASCII run. + + Python IGNORECASE additionally equates i, k and s to non-ASCII characters; + those letters are deliberately excluded. The selected safe run is guaranteed + by any match, while the wildcard matcher still verifies every candidate. + """ + chunks = re.findall(r"[\u3400-\u4DBF\u4E00-\u9FFF0-9a-hjl-rt-zA-HJL-RT-Z]{2,}", query) + # Prefer an available non-ASCII run even when a longer format suffix is + # present: common extensions can otherwise expand tens of thousands of IDs. + native = [chunk for chunk in chunks if any(ord(char) > 127 for char in chunk)] + selected = native or chunks + candidates = get_candidates(max(selected, key=len).lower(), repos) if selected else None + return sorted(get_scope(repos) if candidates is None else candidates) + + +def literal_candidates(query: str, repos: Iterable[str] | None, + get_postings: Callable[[], Mapping[int, PostingIndex]], + get_buffers: Callable[[], Mapping[int, bytes]], + get_repos: Callable[[], Mapping[str, Sequence[int]]], + get_records: Callable[[], Sequence[dict[str, object]]], + get_resolver: Callable[[], PostingResolver]) -> set[int] | None: + """Return an exact posting intersection, or None when no index is usable. + + Index records, repository lists and published postings remain caller-owned. + The first decoded posting is owned by the resolver and may be narrowed in + place exactly as before; no state is cached or published by this helper. + """ + width = 3 if len(query) >= 3 and get_postings().get(3) else 2 + postings = get_postings().get(width) + if not postings or len(query) < width: + return None + entries: list[Posting] = [] + for gram in dict.fromkeys(query[index:index + width] for index in range(len(query) - width + 1)): + encoded = postings.get(gram) + if encoded is None: + return set() + entries.append(encoded) + entries.sort(key=lambda entry: entry[2] if isinstance(entry, tuple) else len(entry)) + candidates: set[int] | None = None + repo_scope = set(repos) if repos else None + for encoded in entries: + matches = get_resolver()(encoded, get_buffers().get(width, b"")) + if candidates is None: + candidates = matches + if repo_scope is not None: + if len(candidates) <= 2048 and sum( + len(get_repos().get(repo, ())) for repo in repo_scope) > len(candidates) * 8: + candidates = {idx for idx in candidates if 0 <= idx < len(get_records()) + and get_records()[idx].get("Repo", "") in repo_scope} + else: + allowed: set[int] = set() + for repo in repo_scope: + allowed.update(get_repos().get(repo, [])) + candidates.intersection_update(allowed) + else: + candidates.intersection_update(matches) + if not candidates: + return set() + return candidates or set() diff --git a/backend/search/domain/filters.py b/backend/search/domain/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b8726969c6a6ebacb0769f70f18845cc34eff9 --- /dev/null +++ b/backend/search/domain/filters.py @@ -0,0 +1,134 @@ +"""Typed search record filters over a caller-owned corpus snapshot.""" +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from typing import cast + +SearchRecord = dict[str, object] +FolderIndex = Mapping[str, Mapping[str, Sequence[int]]] +RepoIndex = Mapping[str, Sequence[int]] + + +def score_record(record: SearchRecord, query_tokens: Iterable[str], search_folders: bool = True) -> int: + score = 0 + file_name = cast(str, record.get("_file_lower", "")) + repo = cast(str, record.get("_repo_lower", "")) + folder_text = cast(str, record.get("_folder_text", "")) + for token in query_tokens: + if token in file_name: + score += 3 + if search_folders and token in folder_text: + score += 2 + if token in repo: + score += 1 + return score + + +def apply_filters(records: Sequence[SearchRecord], indices: Iterable[int], repos: Sequence[str] | None = None, + extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None, + min_size: int | float | None = None, max_size: int | float | None = None, + folder_match_mode: str = "prefix") -> list[int]: + repos_set = set(repos) if repos else None + extensions_lower = {extension.lower() for extension in extensions} if extensions else None + folder_set = {folder.strip("/") for folder in folders} if folders else None + if folder_match_mode != "exact" and folder_set and "" in folder_set: + # Unlike the Worker, an empty API prefix includes the complete scope. + folder_set = None + folder_prefix = next(iter(folder_set)) + "/" if folder_set and len(folder_set) == 1 and folder_match_mode != "exact" else None + result: list[int] = [] + for idx in indices: + record = records[idx] + if repos_set and record.get("Repo") not in repos_set: + continue + if extensions_lower and record.get("_ext_lower", "") not in extensions_lower: + continue + rec_path = "" + if folder_set: + rec_path = (cast(str, record["_folder_path"]) if "_folder_path" in record + else "/".join(cast(list[str], record.get("Folder", []) or []))) + matched = rec_path in folder_set + if not matched and folder_match_mode != "exact": + if folder_prefix is not None: + matched = rec_path.startswith(folder_prefix) + else: + end = rec_path.rfind("/") + while end > 0: + if rec_path[:end] in folder_set: + matched = True + break + end = rec_path.rfind("/", 0, end) + if not matched: + continue + size = record.get("Size") + if size and isinstance(size, (int, float)) and size > 0: + if min_size is not None and size < min_size: + continue + if max_size is not None and size > max_size: + continue + result.append(idx) + return result + + +def apply_mixed_folder_filters(records: Sequence[SearchRecord], indices: Sequence[int], + self_folders: Sequence[str] | None = None, + subtree_folders: Sequence[str] | None = None) -> Sequence[int]: + self_set = {str(path).strip("/") for path in (self_folders or [])} + subtree_set = {str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/")} + if not self_set and not subtree_set: + return indices + result: list[int] = [] + for idx in indices: + rec_folders = cast(list[str], records[idx].get("Folder", []) or []) + rec_path = "/".join(rec_folders) + if rec_path in self_set: + result.append(idx) + continue + if not subtree_set: + continue + if rec_path in subtree_set: + result.append(idx) + continue + matched = False + prefix = "" + for depth, part in enumerate(rec_folders): + # A slash may itself be part of a folder component; only actual + # component boundaries are eligible subtree matches. + prefix = part if depth == 0 else prefix + "/" + part + if prefix in subtree_set: + matched = True + break + if matched: + result.append(idx) + return result + + +def mixed_folder_index_candidates(records: Sequence[SearchRecord], folder_index: FolderIndex, + repo_records_map: RepoIndex, repos: Sequence[str] | None, + self_folders: Sequence[str] | None = None, + subtree_folders: Sequence[str] | None = None) -> list[int] | None: + """Return a bounded corpus-ordered superset, or None to retain a full scan.""" + if len(self_folders or ()) + len(subtree_folders or ()) > 64: + return None + paths = {str(path).strip("/") for path in (self_folders or [])} + paths.update(str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/")) + if not paths: + return None + selected_repos = sorted(set(repos)) if repos else list(repo_records_map) + scope_size = sum(len(repo_records_map.get(repo, ())) for repo in selected_repos) if repos else len(records) + # Broad selections fall back rather than allocating an unbounded set. + limit = min(32768, max(64, scope_size // 2)) + postings: list[Sequence[int]] = [] + estimated = 0 + for repo in selected_repos: + folders = folder_index.get(repo, {}) + for path in paths: + indices = folders.get(path, ()) + estimated += len(indices) + if estimated > limit: + return None + if indices: + postings.append(indices) + candidates: set[int] = set() + for indices in postings: + candidates.update(indices) + return sorted(candidates) diff --git a/backend/search/domain/matching.py b/backend/search/domain/matching.py new file mode 100644 index 0000000000000000000000000000000000000000..652ecdc999df3790981be62641db86494f1d2bb3 --- /dev/null +++ b/backend/search/domain/matching.py @@ -0,0 +1,179 @@ +"""Bounded exact, wildcard and fuzzy search matching.""" +from collections.abc import Callable +import re + + +def compile_exact_matcher(query: str) -> Callable[[str], bool]: + if "*" not in query and "?" not in query: + lower = query.lower() + return lambda text: lower in text.lower() + if not query.strip("*"): + # An unanchored sequence of stars matches the empty substring. + return lambda _text: True + if "*" in query and "?" in query and not query.strip("*?"): + # Stars may match nothing; each question consumes a non-LF code point. + required = query.count("?") + + def matches_question_run(text: str) -> bool: + start = 0 + while start < len(text): + end = text.find("\n", start) + if end < 0: + end = len(text) + if end - start >= required: + return True + start = max(start, end) + 1 + return False + + return matches_question_run + if "*" not in query: + # Escaped fixed-width literals and dots need no variable-length regex + # repetition, retaining IGNORECASE and dot's LF behavior. + fixed = re.compile("".join("." if char == "?" else re.escape(char) for char in query), re.IGNORECASE) + if len(query) < 128 or not any(char != "?" for char in query): + return lambda text: fixed.search(text) is not None + literals = [re.compile(re.escape(char), re.IGNORECASE) + for char in dict.fromkeys(query) if char != "?"] + return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals)) + and fixed.search(text) is not None) + # In substring matching, stars at either boundary can match zero chars. + # Keep Unicode IGNORECASE behavior, unlike the literal .lower() branch. + core = query.strip("*") + if core and "*" not in core and "?" not in core: + literal = re.compile(re.escape(core), re.IGNORECASE) + return lambda text: literal.search(text) is not None + if "*" in core and "?" not in core and "\n" not in core: + # A leftmost match for each mandatory chunk leaves the most room for + # later chunks. Wildcard dots cannot cross LF in Python's regex rules. + chunks = [re.compile(re.escape(part), re.IGNORECASE) + for part in re.split(r"\*+", core)] + + def matches_chunks(text: str) -> bool: + for line in text.split("\n"): + position = 0 + for chunk in chunks: + match = chunk.search(line, position) + if match is None: + break + position = match.end() + else: + return True + return False + + return matches_chunks + # A leading/trailing wildcard run followed/preceded by a fixed literal + # has only one variable-width part. Strip its boundary stars: they can + # always match zero characters in an unanchored search. The remaining + # questions have fixed width and therefore cannot backtrack exponentially. + core_parts = core.split("*") + nonempty_parts = [part for part in core_parts if part] + if len(nonempty_parts) == 2: + first, last = nonempty_parts + first_questions = first and not first.strip("?") and "?" not in last + last_questions = last and not last.strip("?") and "?" not in first + if first_questions or last_questions: + fixed = first + last + expression = re.compile("".join("." if char == "?" else re.escape(char) for char in fixed), re.IGNORECASE) + if len(fixed) >= 128: + literals = [re.compile(re.escape(char), re.IGNORECASE) + for char in dict.fromkeys(fixed) if char != "?"] + return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals)) + and expression.search(text) is not None) + return lambda text: expression.search(text) is not None + # Bitset NFA: each bit is a pattern position. Collapse adjacent stars so + # epsilon closure needs one shift. No input can cause regex backtracking. + pattern = re.sub(r"\*+", "*", query) + stars = questions = 0 + literal_bits: dict[str, int] = {} + for index, char in enumerate(pattern): + bit = 1 << index + if char == "*": + stars |= bit + elif char == "?": + questions |= bit + else: + literal_bits[char] = literal_bits.get(char, 0) | bit + # Single-character regexes retain Python IGNORECASE's Unicode semantics. + literals = [(re.compile(re.escape(char), re.IGNORECASE), bits) + for char, bits in literal_bits.items()] + masks: dict[str, int] = {} + end = 1 << len(pattern) + start = 1 | ((1 & stars) << 1) + + def matches(text: str) -> bool: + # Every literal is mandatory; C-level scans reject unrelated fields early. + if any(regex.search(text) is None for regex, _ in literals): + return False + active = start + for char in text: + mask = masks.get(char) + if mask is None: + mask = sum(bits for regex, bits in literals if regex.fullmatch(char)) + if len(masks) >= 512: + masks.clear() + masks[char] = mask + wildcard = char != "\n" + active = ((active & (mask | (questions if wildcard else 0))) << 1) | ( + active & stars if wildcard else 0) | 1 + active |= (active & stars) << 1 + if active & end: + return True + return False + return matches + + +def matches_exact_query(text: str, query: str) -> bool: + return compile_exact_matcher(query)(text) + + +def split_exact_terms(query: str) -> list[str]: + """Whitespace separates literal terms; each term must match independently.""" + return [term for term in query.split() if term] + +def edit_distance(s1: str, s2: str, max_dist: int = 2) -> int: + if abs(len(s1) - len(s2)) > max_dist: + return 999 + prev = list(range(len(s2) + 1)) + for i, c1 in enumerate(s1): + curr = [i + 1] + for j, c2 in enumerate(s2): + cost = 0 if c1 == c2 else 1 + curr.append(min(prev[j + 1] + 1, curr[j] + 1, prev[j] + cost)) + if min(curr) > max_dist: + return 999 + prev = curr + return prev[-1] + +def could_be_fuzzy(tok: str, word: str, max_dist: int = 2) -> bool: + if abs(len(tok) - len(word)) > max_dist: + return False + if len(tok) < 4: + return True + counts: dict[str, int] = {} + for ch in tok: + counts[ch] = counts.get(ch, 0) + 1 + diff = 0 + for ch in word: + if counts.get(ch, 0) > 0: + counts[ch] -= 1 + else: + diff += 1 + if diff > 2 * max_dist: + return False + for remaining in counts.values(): + diff += remaining + if diff > 2 * max_dist: + return False + return True + + +def fuzzy_distance_budget(token: str) -> int: + """Short tokens cannot tolerate the same edit radius as longer words.""" + if len(token) <= 1: + return 0 + return 1 if len(token) <= 3 else 2 + + +def is_fuzzy_match(token: str, word: str) -> bool: + limit = fuzzy_distance_budget(token) + return could_be_fuzzy(token, word, limit) and edit_distance(token, word, max_dist=limit) <= limit diff --git a/backend/search/domain/ordering.py b/backend/search/domain/ordering.py index c3ed21865713b7e38e2e92365187ff71b5387d80..b7387bdaf678d18ade2146006bb9affdb842bbf5 100644 --- a/backend/search/domain/ordering.py +++ b/backend/search/domain/ordering.py @@ -10,8 +10,8 @@ from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass from typing import Protocol, TypedDict, cast -from backend.search_browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilter -from backend.search_indexes import Posting +from backend.search.domain.browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilter +from backend.search.corpus.infrastructure.indexes import Posting Record = dict[str, object] Paths = Sequence[str] | None diff --git a/backend/search/domain/term_candidates.py b/backend/search/domain/term_candidates.py new file mode 100644 index 0000000000000000000000000000000000000000..848acc2263be20723fa7774224af2ffaeeba9082 --- /dev/null +++ b/backend/search/domain/term_candidates.py @@ -0,0 +1,129 @@ +"""Word and fuzzy candidate selection for a single search term.""" +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from typing import cast + +from backend.search.infrastructure.executor import check_search_cancelled + +SearchRecord = dict[str, object] + + +def term_candidates(term: str, query_token_count: int, posting_cache: dict[str, set[int]], + search_folders: bool, *, tokenize: Callable[[str], list[str]], + scoped_word_postings: Callable[[str, bool], set[int]], + get_word_index: Callable[[], Mapping[str, object]], + get_records: Callable[[], Sequence[SearchRecord]], + get_vocab: Callable[[], Mapping[int, list[str]]], + is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]: + """Intersect term postings without truncating before record filters.""" + query_tokens = tokenize(term) + return candidates_for_tokens(query_tokens, query_token_count, posting_cache, search_folders, + tokenize=tokenize, scoped_word_postings=scoped_word_postings, + get_word_index=get_word_index, get_records=get_records, get_vocab=get_vocab, + is_fuzzy_match=is_fuzzy_match) + + +def candidates_for_tokens(query_tokens: Sequence[str], query_token_count: int, posting_cache: dict[str, set[int]], + search_folders: bool, *, tokenize: Callable[[str], list[str]], + scoped_word_postings: Callable[[str, bool], set[int]], + get_word_index: Callable[[], Mapping[str, object]], + get_records: Callable[[], Sequence[SearchRecord]], + get_vocab: Callable[[], Mapping[int, list[str]]], + is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]: + """Resolve already-tokenized input without repeating tokenization.""" + # Candidate caps before repository and record filtering can lose valid hits. + fuzzy_candidate_limit = None + fuzzy_tokens: set[str] = set() + + def query_postings(token: str) -> set[int]: + if token not in posting_cache: + posting_cache[token] = scoped_word_postings(token, search_folders) + return posting_cache[token] + + exact_constraint = _exact_constraint(query_tokens, get_word_index, query_postings) + token_candidates: list[set[int]] = [] + for tok in query_tokens: + check_search_cancelled() + candidates: set[int] = query_postings(tok) if tok in get_word_index() else set() + if not candidates: + fuzzy_tokens.add(tok) + candidates = _fuzzy_candidates(tok, exact_constraint, fuzzy_candidate_limit, search_folders, + get_records, get_vocab, tokenize, is_fuzzy_match, query_postings) + if not candidates: + return set(), fuzzy_tokens + token_candidates.append(candidates) + return _intersect_candidates(token_candidates), fuzzy_tokens + + +def _exact_constraint(query_tokens: Sequence[str], get_word_index: Callable[[], Mapping[str, object]], + query_postings: Callable[[str], set[int]]) -> set[int] | None: + exact_constraint: set[int] | None = None + for tok in query_tokens: + if tok not in get_word_index(): + continue + postings = query_postings(tok) + if not postings: + continue + exact_constraint = set(postings) if exact_constraint is None else exact_constraint.intersection(postings) + return exact_constraint + + +def _intersect_candidates(token_candidates: list[set[int]]) -> set[int]: + if not token_candidates: + return set() + token_candidates.sort(key=len) + matched = set(token_candidates[0]) + for candidates in token_candidates[1:]: + matched.intersection_update(candidates) + if not matched: + break + return matched + + +def _fuzzy_candidates(tok: str, exact_constraint: set[int] | None, limit: int | None, search_folders: bool, + get_records: Callable[[], Sequence[SearchRecord]], + get_vocab: Callable[[], Mapping[int, list[str]]], tokenize: Callable[[str], list[str]], + is_fuzzy_match: Callable[[str, str], bool], + query_postings: Callable[[str], set[int]]) -> set[int]: + if exact_constraint is not None: + return _fuzzy_record_candidates(tok, exact_constraint, limit, search_folders, + get_records, tokenize, is_fuzzy_match) + return _fuzzy_vocabulary_candidates(tok, limit, get_vocab, is_fuzzy_match, query_postings) + + +def _fuzzy_record_candidates(tok: str, exact_constraint: set[int], limit: int | None, search_folders: bool, + get_records: Callable[[], Sequence[SearchRecord]], + tokenize: Callable[[str], list[str]], + is_fuzzy_match: Callable[[str, str], bool]) -> set[int]: + candidates: set[int] = set() + for offset, idx in enumerate(sorted(exact_constraint)): + if offset % 256 == 0: + check_search_cancelled() + rec = get_records()[idx] + record_tokens = tokenize(" ".join([cast(str, rec.get("File", "")), + *(cast(list[str], rec.get("Folder", []) or []) if search_folders else [])])) + if any(is_fuzzy_match(tok, word) for word in record_tokens): + candidates.add(idx) + if limit is not None and len(candidates) >= limit: + break + return candidates + + +def _fuzzy_vocabulary_candidates(tok: str, limit: int | None, + get_vocab: Callable[[], Mapping[int, list[str]]], + is_fuzzy_match: Callable[[str, str], bool], + query_postings: Callable[[str], set[int]]) -> set[int]: + candidates: set[int] = set() + tok_len = len(tok) + for delta in (-2, -1, 0, 1, 2): + for offset, vocab_word in enumerate(get_vocab().get(tok_len + delta, [])): + if offset % 256 == 0: + check_search_cancelled() + if is_fuzzy_match(tok, vocab_word): + candidates.update(query_postings(vocab_word)) + if limit is not None and len(candidates) >= limit: + break + if limit is not None and len(candidates) >= limit: + break + return candidates diff --git a/backend/search/http/body_limit.py b/backend/search/http/body_limit.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab1fddc1f614dadbd52247f9c935e2e53ea9478 --- /dev/null +++ b/backend/search/http/body_limit.py @@ -0,0 +1,64 @@ +"""Bound search uploads before JSON parsing; leave application failures untouched.""" +import asyncio + +from starlette.responses import Response +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +SEARCH_BODY_MAX_BYTES = 8 * 1024 * 1024 +SEARCH_BODY_TIMEOUT_SECONDS = 15.0 + + +class SearchBodyLimitMiddleware: + def __init__(self, app: ASGIApp) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + path = scope.get("path", "") + if (scope["type"] != "http" or scope["method"] != "POST" + or not (path == "/api/search" or path.startswith("/api/search/"))): + await self.app(scope, receive, send) + return + # Count actual wire bytes, including chunked uploads and misleading + # Content-Length. A bytearray also bounds overhead from tiny chunks. + body = bytearray() + status = None + chunk = b"" + message: Message = {} + deadline = asyncio.timeout(SEARCH_BODY_TIMEOUT_SECONDS) + try: + async with deadline: + while True: + message = await receive() + if message["type"] == "http.disconnect": + status = 204 + break + chunk = message.get("body", b"") + if len(body) + len(chunk) > SEARCH_BODY_MAX_BYTES: + status = 413 + break + body.extend(chunk) + if not message.get("more_body", False): + break + # receive may complete synchronously for buffered messages. + await asyncio.sleep(0) + except TimeoutError: + if not deadline.expired(): + raise + status = 408 + del message, chunk + if status is not None: + body.clear() + await Response(status_code=status, headers={"Cache-Control": "no-store"})(scope, receive, send) + return + buffered: bytes | None = bytes(body) + body.clear() + + async def replay() -> Message: + nonlocal buffered + if buffered is not None: + payload, buffered = buffered, None + return {"type": "http.request", "body": payload, "more_body": False} + return await receive() + + # The upload deadline ends before validation, routing or response send. + await self.app(scope, replay, send) diff --git a/backend/search/http/responses.py b/backend/search/http/responses.py index 74d832b153236fb218368834d7deff6acaac65f4..43bc0c6c5ba06b7ac38c95cd3c20f16fed6917fc 100644 --- a/backend/search/http/responses.py +++ b/backend/search/http/responses.py @@ -14,7 +14,7 @@ from backend.search.application.requests import ( NormalizeSearchList, SearchFunction, SearchParameters, normalize_search_parameters, ) from backend.search.http.schemas import SearchRequest -from backend.search_execution import SearchBusy +from backend.search.infrastructure.executor import SearchBusy JsonObject = dict[str, object] diff --git a/backend/search/infrastructure/__init__.py b/backend/search/infrastructure/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ec88663cf7ec90ef1b3312e788936205ba64d76 --- /dev/null +++ b/backend/search/infrastructure/__init__.py @@ -0,0 +1 @@ +"""search infrastructure package.""" diff --git a/backend/search/infrastructure/executor.py b/backend/search/infrastructure/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..b868e019b72b5645a005c59147fa034d0864d8c7 --- /dev/null +++ b/backend/search/infrastructure/executor.py @@ -0,0 +1,165 @@ +"""One owned search thread; active work retains its slot until it exits.""" +import asyncio +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +import logging +import time +import threading +from types import TracebackType +from typing import TypeVar + + +logger = logging.getLogger("backend.search_execution") + +T = TypeVar("T") + + +class SearchCancelled(Exception): + """The requester left while a cooperative search was running.""" + + +class SearchBusy(Exception): + pass + + +_search_thread = threading.local() + + +def check_search_cancelled() -> None: + event = getattr(_search_thread, "cancelled", None) + if event is not None and event.is_set(): + raise SearchCancelled() + + +def _report_close_failure(task: asyncio.Task[None], state: dict[str, int | bool]) -> None: + if task.done() and not task.cancelled(): + error = task.exception() + if error is not None and not state["waiters"] and not state["observed"]: + state["observed"] = True + task.get_loop().call_exception_handler({ + "message": "SearchExecutor close failed without a waiting caller", + "exception": error, + "task": task, + }) + + +class SearchExecutor: + def __init__(self, capacity: int = 32) -> None: + self.capacity = capacity + self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="search") + self._lock = asyncio.Lock() + self._tasks: set[asyncio.Task[tuple[object, float, float]]] = set() + self._closing = False + self._close_task: asyncio.Task[None] | None = None + self._close_state: dict[str, int | bool] | None = None + self._foreground: set[asyncio.Task[tuple[object, float, float]]] = set() + + async def __aenter__(self) -> "SearchExecutor": + return self + + async def __aexit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, + traceback: TracebackType | None) -> None: + await self.close() + + async def run(self, function: Callable[[], T], *, background: bool = False) -> tuple[T, float, float]: + if self._closing or len(self._tasks) >= self.capacity: + raise SearchBusy() + job = {"started": False} + cancelled = threading.Event() + queued = time.perf_counter() + predecessors = tuple(self._foreground) if background else () + + def compute() -> tuple[T, float, float]: + started = time.perf_counter() + _search_thread.cancelled = cancelled + try: + check_search_cancelled() + result = function() + return result, (started - queued) * 1000, (time.perf_counter() - started) * 1000 + finally: + del _search_thread.cancelled + + async def execute() -> tuple[T, float, float]: + if predecessors: + await asyncio.wait(predecessors) + async with self._lock: + job["started"] = True + return await asyncio.get_running_loop().run_in_executor(self._pool, compute) + + task = asyncio.create_task(execute()) + self._tasks.add(task) + if not background: + self._foreground.add(task) + + def finished(done: asyncio.Task[tuple[T, float, float]]) -> None: + self._tasks.discard(done) + self._foreground.discard(done) + if not done.cancelled(): + done.exception() # Consume failures when the requester has left. + + task.add_done_callback(finished) + try: + return await asyncio.shield(task) + except asyncio.CancelledError: + cancelled.set() + if not job["started"]: + task.cancel() # Queued work has no side effects and can be dropped. + raise + + async def close(self) -> None: + if (self._close_task is None or + (self._close_task.done() and + (self._close_task.cancelled() or self._close_task.exception() is not None))): + self._closing = True + + async def drain() -> None: + await asyncio.gather(*self._tasks, return_exceptions=True) + loop = asyncio.get_running_loop() + joined = loop.create_future() + + def notify(error: BaseException | None) -> None: + if not joined.done(): + if error is None: + joined.set_result(None) + else: + joined.set_exception(error) + + def shutdown() -> None: + error = None + try: + self._pool.shutdown(wait=True) + except BaseException as exc: + error = exc + # Log in the worker: even a successfully queued callback may + # never run if the loop closes, or its future is cancelled. + logger.exception("SearchExecutor shutdown failed") + try: + loop.call_soon_threadsafe(notify, error) + except RuntimeError: + # The host must keep the loop alive until close completes. + pass + + threading.Thread(target=shutdown, name="search-shutdown").start() + await joined + + self._close_task = asyncio.create_task(drain()) + close_state: dict[str, int | bool] = {"waiters": 0, "observed": False} + self._close_state = close_state + + self._close_task.add_done_callback(lambda task: _report_close_failure(task, close_state)) + task = self._close_task + state = self._close_state + if state is None: + raise RuntimeError("SearchExecutor close state missing") + state["waiters"] += 1 + try: + # A cancelled caller must not cancel the drain or its owned jobs. + await asyncio.shield(task) + except asyncio.CancelledError: + raise + except BaseException: + state["observed"] = True + raise + finally: + state["waiters"] -= 1 + _report_close_failure(task, state) diff --git a/backend/search/infrastructure/runtime_entry.py b/backend/search/infrastructure/runtime_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..0bac3522f7a2828663cf6b2b4d8ce52386f7c88b --- /dev/null +++ b/backend/search/infrastructure/runtime_entry.py @@ -0,0 +1,73 @@ +"""Optional Uvicorn entry point selecting a verified Space search generation. + +Without configuration the original ASGI application is used unchanged. If a +candidate is configured, its complete file set and index structure are checked +before the application starts. A failed candidate stops startup and never mixes +files with the bundled fallback. The original ASGI generation identifier remains +unchanged; the independent health endpoint reports the selected bucket identity. +""" +from __future__ import annotations + +import json +import os +from collections.abc import AsyncGenerator, Awaitable, Callable +from contextlib import asynccontextmanager +from pathlib import Path + +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse, Response + +from backend.search.corpus.infrastructure.selection import inspect_generation + + +def selected_app() -> FastAPI: + generation = os.environ.get("SEARCH_DATA_GENERATION", "") + directory = os.environ.get("SEARCH_DATA_DIRECTORY", "") + if bool(generation) != bool(directory): + raise RuntimeError("SEARCH_DATA_GENERATION and SEARCH_DATA_DIRECTORY must be set together") + selected = inspect_generation(Path(directory), generation) if generation else None + from backend import app as service + if selected is None: + return service.app + root = selected.directory + service.DATA_PATH = root / "search_data.json.gz" + service.NGRAM_PATHS = {2: root / "search_ngrams_2.bin.gz", 3: root / "search_ngrams_3.bin.gz"} + service.WORD_INDEX_PATH = root / "search_words.bin.gz" + service.FOLDER_TREE_PATH = root / "folder_tree.json.gz" + service.FOLDER_BROWSER_PATH = root / "folder_browser.json.gz" + service.SIDEBAR_DATA_PATH = root / "sidebar" + original_lifespan = service.app.router.lifespan_context + + @asynccontextmanager + async def verified_lifespan(application: FastAPI) -> AsyncGenerator[None, None]: + async with original_lifespan(application): + if (len(service.records) != selected.record_count or not service.word_index + or not service.ngram_postings.get(2) or not service.ngram_postings.get(3)): + raise RuntimeError("selected search generation did not load completely") + application.state.selected_search_generation = selected.generation + application.state.selected_search_files = selected.file_count + application.state.selected_search_records = len(service.records) + print(json.dumps({"kind": "search-generation-loaded", "generation": selected.generation, + "surface": "space", "files_verified": selected.file_count, + "records_loaded": len(service.records), "api_generation": service.search_generation()}), + flush=True) + yield + + service.app.router.lifespan_context = verified_lifespan + + @service.app.middleware("http") + async def generation_status(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response: + if request.url.path == "/api/search-data-generation": + current = getattr(request.app.state, "selected_search_generation", None) + if current != selected.generation: + return JSONResponse({"error": "generation not loaded"}, status_code=503) + return JSONResponse({"generation": current, "surface": "space", "verified": True, + "files": selected.file_count, "records": len(service.records), + "api_generation": service.search_generation()}, + headers={"Cache-Control": "no-store"}) + return await call_next(request) + + return service.app + + +app = selected_app() diff --git a/backend/search_bootstrap.py b/backend/search_bootstrap.py index ac5a8beda523c9f3ee14d88b5f3e82765705989c..bdea75d31755861754a209b3854f749ba11831c0 100644 --- a/backend/search_bootstrap.py +++ b/backend/search_bootstrap.py @@ -1,31 +1,10 @@ -"""Typed construction of initial search pages from caller-owned state.""" -from __future__ import annotations - -from collections.abc import Callable, Iterable, Mapping, Sequence - -SearchRecord = dict[str, object] - - -def trim_initial_results(raw: Iterable[SearchRecord]) -> list[SearchRecord]: - return [{"Repo": record.get("Repo", ""), "File": record.get("File", ""), - "Extension": record.get("Extension", ""), "Folder": record.get("Folder", []), - "Size": record.get("Size", ""), "HasTxt": record.get("HasTxt", "")} for record in raw] - - -def build_initial_payload(repo: str | None, get_page_size: Callable[[], int], - get_repos: Callable[[], Mapping[str, Sequence[int]]], - get_records: Callable[[], Sequence[SearchRecord]], - get_trim: Callable[[], Callable[[Sequence[SearchRecord]], list[SearchRecord]]], - get_generation: Callable[[], Callable[[], str]]) -> dict[str, object]: - """Preserve snapshot lookup, projection and generation evaluation order.""" - if repo: - indices = get_repos().get(repo, []) - result_records = [get_records()[index] for index in indices[:get_page_size()]] - mode = "repo" - total = len(indices) - else: - result_records = get_records()[:get_page_size()] - mode = "global" - total = len(get_records()) - return {"mode": mode, "repo": repo, "sort": "relevance", "page": 1, "page_size": get_page_size(), - "total": total, "results": get_trim()(result_records), "generation": get_generation()()} +"""Compatibility import for backend.search.application.bootstrap.""" +import sys +from backend.search.application import bootstrap as _implementation +from backend.search.application.bootstrap import ( + SearchRecord as SearchRecord, + build_initial_payload as build_initial_payload, + trim_initial_results as trim_initial_results, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_browse.py b/backend/search_browse.py index ddcdb253963172ce94026e9b041cd8b681b361b9..516b8aea57de5ed30b3c24570b0c08e59a379584 100644 --- a/backend/search_browse.py +++ b/backend/search_browse.py @@ -1,47 +1,14 @@ -"""Plan empty-query browsing against caller-owned search indexes.""" -from __future__ import annotations - -from collections.abc import Callable, Sequence - -Size = int | float | None -Paths = Sequence[str] | None -RecordFilter = Callable[[Sequence[int], Paths, Paths, Paths, Size, Size, str], list[int]] -MixedRecordFilter = Callable[[Sequence[int], Paths, Paths, Size, Size], list[int]] -MixedFilter = Callable[[Sequence[int], Paths, Paths], Sequence[int]] -MixedCandidates = Callable[[Paths, Paths, Paths], list[int] | None] - - -def browse_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size, - folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths, sort: str, *, - get_precomputed: Callable[[Paths, str], Sequence[int]], - get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]], - filter_mixed: MixedFilter, filter_records: RecordFilter, - filter_mixed_records: MixedRecordFilter, key_name: Callable[[int], str], key_size: Callable[[int], tuple[int | float, str]]) -> Sequence[int]: - """Preserve precomputed order identity or filter a bounded corpus snapshot.""" - has_filters = (extensions or folders or min_size is not None or max_size is not None - or folder_match_mode == "mixed") - if not has_filters and (not repos or len(repos) == 1): - return get_precomputed(repos, sort) - filtered = _filtered_order(repos, extensions, folders, min_size, max_size, folder_match_mode, - folder_selfs, folder_subtrees, get_mixed_candidates, get_initial, - filter_mixed, filter_records, filter_mixed_records) - if sort == "name": - filtered.sort(key=key_name) - elif sort == "size": - filtered.sort(key=key_size) - return filtered - - -def _filtered_order(repos: Paths, extensions: Paths, folders: Paths, min_size: Size, max_size: Size, - folder_match_mode: str, folder_selfs: Paths, folder_subtrees: Paths, - get_mixed_candidates: MixedCandidates, get_initial: Callable[[Paths], Sequence[int]], - filter_mixed: MixedFilter, filter_records: RecordFilter, - filter_mixed_records: MixedRecordFilter) -> list[int]: - if folder_match_mode == "mixed": - indices = get_mixed_candidates(repos, folder_selfs, folder_subtrees) - if indices is None: - indices = get_initial(repos) - mixed = filter_mixed(indices, folder_selfs, folder_subtrees) - return filter_mixed_records(mixed, repos, extensions, min_size, max_size) - indices = get_initial(repos) - return filter_records(indices, repos, extensions, folders, min_size, max_size, folder_match_mode) +"""Compatibility import for backend.search.domain.browse.""" +import sys +from backend.search.domain import browse as _implementation +from backend.search.domain.browse import ( + MixedCandidates as MixedCandidates, + MixedFilter as MixedFilter, + MixedRecordFilter as MixedRecordFilter, + Paths as Paths, + RecordFilter as RecordFilter, + Size as Size, + browse_order as browse_order, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_candidates.py b/backend/search_candidates.py index 220cbb688bb847770bd713ec66302708eaf3b03b..a37b0263e1554b7a9d01f32dcb3bf31b74605dff 100644 --- a/backend/search_candidates.py +++ b/backend/search_candidates.py @@ -1,72 +1,10 @@ -"""Typed literal n-gram candidate selection over caller-owned search state.""" -from __future__ import annotations - -from collections.abc import Callable, Iterable, Mapping, Sequence -import re -from backend.search_indexes import Posting, PostingIndex - -PostingResolver = Callable[[Posting, bytes], set[int]] - - -def wildcard_literal_candidates(query: str, repos: Iterable[str] | None, - get_candidates: Callable[[str, Iterable[str] | None], set[int] | None], - get_scope: Callable[[Iterable[str] | None], Sequence[int]]) -> list[int]: - """Bound wildcard search by a safe mandatory CJK, digit or ASCII run. - - Python IGNORECASE additionally equates i, k and s to non-ASCII characters; - those letters are deliberately excluded. The selected safe run is guaranteed - by any match, while the wildcard matcher still verifies every candidate. - """ - chunks = re.findall(r"[\u3400-\u4DBF\u4E00-\u9FFF0-9a-hjl-rt-zA-HJL-RT-Z]{2,}", query) - # Prefer an available non-ASCII run even when a longer format suffix is - # present: common extensions can otherwise expand tens of thousands of IDs. - native = [chunk for chunk in chunks if any(ord(char) > 127 for char in chunk)] - selected = native or chunks - candidates = get_candidates(max(selected, key=len).lower(), repos) if selected else None - return sorted(get_scope(repos) if candidates is None else candidates) - - -def literal_candidates(query: str, repos: Iterable[str] | None, - get_postings: Callable[[], Mapping[int, PostingIndex]], - get_buffers: Callable[[], Mapping[int, bytes]], - get_repos: Callable[[], Mapping[str, Sequence[int]]], - get_records: Callable[[], Sequence[dict[str, object]]], - get_resolver: Callable[[], PostingResolver]) -> set[int] | None: - """Return an exact posting intersection, or None when no index is usable. - - Index records, repository lists and published postings remain caller-owned. - The first decoded posting is owned by the resolver and may be narrowed in - place exactly as before; no state is cached or published by this helper. - """ - width = 3 if len(query) >= 3 and get_postings().get(3) else 2 - postings = get_postings().get(width) - if not postings or len(query) < width: - return None - entries: list[Posting] = [] - for gram in dict.fromkeys(query[index:index + width] for index in range(len(query) - width + 1)): - encoded = postings.get(gram) - if encoded is None: - return set() - entries.append(encoded) - entries.sort(key=lambda entry: entry[2] if isinstance(entry, tuple) else len(entry)) - candidates: set[int] | None = None - repo_scope = set(repos) if repos else None - for encoded in entries: - matches = get_resolver()(encoded, get_buffers().get(width, b"")) - if candidates is None: - candidates = matches - if repo_scope is not None: - if len(candidates) <= 2048 and sum( - len(get_repos().get(repo, ())) for repo in repo_scope) > len(candidates) * 8: - candidates = {idx for idx in candidates if 0 <= idx < len(get_records()) - and get_records()[idx].get("Repo", "") in repo_scope} - else: - allowed: set[int] = set() - for repo in repo_scope: - allowed.update(get_repos().get(repo, [])) - candidates.intersection_update(allowed) - else: - candidates.intersection_update(matches) - if not candidates: - return set() - return candidates or set() +"""Compatibility import for backend.search.domain.candidates.""" +import sys +from backend.search.domain import candidates as _implementation +from backend.search.domain.candidates import ( + PostingResolver as PostingResolver, + literal_candidates as literal_candidates, + wildcard_literal_candidates as wildcard_literal_candidates, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_data_selector.py b/backend/search_data_selector.py index 62c3f40864f2154b4e8039e5a36fa6cf1e27abc3..3a02dc4fff81ac6f0901bcc75056744ac377054c 100644 --- a/backend/search_data_selector.py +++ b/backend/search_data_selector.py @@ -1,290 +1,22 @@ -"""Select a verified, immutable local search-data generation before startup. - -The caller supplies the build-materialized directory. Selection is opt-in and -all-or-nothing: hashes, lengths, path containment and gzip/JSON structure are -checked before any application paths are changed. This module never writes a -bucket pointer or downloads data and does not replace a running process's data. -""" -from __future__ import annotations - -import gzip -import hashlib -import json -import re -from dataclasses import dataclass -from pathlib import Path -from typing import cast -from urllib.parse import quote - -from .search_indexes import load_ngram_index, load_word_index - - -SHA = re.compile(r"[0-9a-f]{64}\Z") -MANDATORY = frozenset({"search_data.json.gz", "folder_tree.json.gz", "folder_browser.json.gz", - "search_words.bin.gz", "search_ngrams_2.bin.gz", "search_ngrams_3.bin.gz", - "initial/global.json", "initial/manifest.json", "sidebar/global.json", "sidebar/manifest.json"}) -MAX_FILE = 32 * 1024 * 1024 -MAX_EXPANDED = 256 * 1024 * 1024 -MAX_FILES = 1024 - - -def as_mapping(value: object, label: str) -> dict[str, object]: - if not isinstance(value, dict): - raise ValueError(f"{label} must be an object") - mapping = cast(dict[object, object], value) - if any(not isinstance(key, str) for key in mapping): - raise ValueError(f"{label} keys must be strings") - return cast(dict[str, object], mapping) - - -def as_list(value: object, label: str) -> list[object]: - if not isinstance(value, list): - raise ValueError(f"{label} must be an array") - return cast(list[object], value) - - -def canonical(value: object) -> bytes: - return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), - allow_nan=False) + "\n").encode("utf-8") - - -def read_compressed_mapping(path: Path, label: str) -> dict[str, object]: - """Bound expanded generated JSON before interpreting any directory data.""" - try: - with gzip.open(path, "rb") as stream: - raw = stream.read(MAX_EXPANDED + 1) - except (OSError, EOFError) as error: - raise ValueError(f"invalid compressed {label}") from error - if len(raw) > MAX_EXPANDED: - raise ValueError(f"expanded {label} exceeds limit") - try: - return as_mapping(json.loads(raw), label) - except (UnicodeDecodeError, json.JSONDecodeError) as error: - raise ValueError(f"invalid {label} JSON") from error - - -def read_json_mapping(path: Path, label: str) -> dict[str, object]: - try: - return as_mapping(json.loads(path.read_bytes()), label) - except (UnicodeDecodeError, json.JSONDecodeError) as error: - raise ValueError(f"invalid {label} JSON") from error - - -def append_bootstrap_record(global_prefix: list[dict[str, object]], repo_prefix: list[dict[str, object]], - record: dict[str, object]) -> None: - """Keep bounded prefixes; avoid retaining every decoded corpus record.""" - if len(global_prefix) < 500: - global_prefix.append(record) - if len(repo_prefix) < 500: - repo_prefix.append(record) - - -def validate_directory_data(root: Path, repos: list[str]) -> dict[str, dict[str, object]]: - tree = read_compressed_mapping(root / "folder_tree.json.gz", "Space folder tree") - browser = read_compressed_mapping(root / "folder_browser.json.gz", "Space folder browser") - if set(tree) != set(repos) or set(browser) != set(repos): - raise ValueError("Space directory repositories mismatch") - roots: dict[str, dict[str, object]] = {} - for repo in repos: - nodes = as_list(tree[repo], "Space folder roots") - pending = list(nodes) - while pending: - node = as_mapping(pending.pop(), "Space folder node") - if not isinstance(node.get("n"), str) or type(node.get("c")) is not int or cast(int, node["c"]) < 0: - raise ValueError("invalid Space folder node") - if not isinstance(node.get("df"), bool): - raise ValueError("invalid Space folder node") - pending.extend(as_list(node.get("ch"), "Space folder children")) - paths = as_mapping(browser[repo], "Space folder browser paths") - if "" not in paths: - raise ValueError("Space folder browser root missing") - for path, value in paths.items(): - entry = as_mapping(value, "Space folder browser entry") - for folder in as_list(entry.get("d"), "Space folder browser folders"): - item = as_mapping(folder, "Space folder browser folder") - if not isinstance(item.get("n"), str) or type(item.get("c")) is not int or cast(int, item["c"]) < 0: - raise ValueError("invalid Space folder browser folder") - for file in as_list(entry.get("f"), "Space folder browser files"): - item = as_mapping(file, "Space folder browser file") - if (not isinstance(item.get("n"), str) or not isinstance(item.get("e"), str) - or not isinstance(item.get("t"), bool) - or not isinstance(item.get("s"), (int, str)) or isinstance(item.get("s"), bool)): - raise ValueError("invalid Space folder browser file") - if path == "": - roots[repo] = entry - return roots - - -def safe_name(name: object) -> bool: - if (not isinstance(name, str) or not name or name.startswith("/") or "\\" in name - or any(part in {"", ".", ".."} for part in name.split("/")) - or any(ord(char) < 32 or ord(char) == 127 for char in name)): - return False - return name in MANDATORY or bool(re.fullmatch(r"(?:initial|sidebar)/repos/[^/]+\.json", name)) - - -@dataclass(frozen=True) -class SelectedGeneration: - generation: str - directory: Path - file_count: int - record_count: int - - -def inspect_generation(directory: Path, generation: str) -> SelectedGeneration: - """Verify every advertised Space member and return the immutable selection.""" - if not SHA.fullmatch(generation): - raise ValueError("invalid search generation identity") - if directory.is_symlink() or not directory.is_dir(): - raise ValueError("generation directory must be an ordinary directory") - root = directory.resolve() - report_file = root / "generation-manifest.json" - if report_file.is_symlink() or not report_file.is_file() or report_file.stat().st_size > 1024 * 1024: - raise ValueError("missing or oversized local generation manifest") - raw_manifest = report_file.read_bytes() - manifest = as_mapping(json.loads(raw_manifest), "search generation manifest") - if (manifest.get("version") != 1 or manifest.get("kind") != "search-snapshot-local" - or manifest.get("generation") != generation - or manifest.get("object_layout") != "objects/sha256//"): - raise ValueError("invalid search generation manifest") - excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"} - identity = {key: value for key, value in manifest.items() if key not in excluded} - if hashlib.sha256(canonical(identity)).hexdigest() != generation: - raise ValueError("search manifest identity mismatch") - objects = as_mapping(manifest.get("objects"), "generation objects") - files = as_mapping(manifest.get("files"), "generation files") - entries = as_mapping(objects.get("space"), "Space objects") - original = as_mapping(files.get("space"), "Space files") - if set(entries) != set(original): - raise ValueError("Space manifest member mismatch") - actual: set[str] = set() - for path in root.rglob("*"): - if path.is_symlink(): - raise ValueError("symlinks are forbidden in generation files") - if path.is_file() and path != report_file: - actual.add(path.relative_to(root).as_posix()) - elif not path.is_dir() and path != report_file: - raise ValueError("generation contains a non-file object") - if actual != set(entries): - raise ValueError("Space generation contains missing or unlisted files") - if not MANDATORY <= set(entries) or len(entries) > MAX_FILES: - raise ValueError("Space generation is incomplete") - for name, item in entries.items(): - if not safe_name(name): - raise ValueError("invalid Space member") - metadata = as_mapping(item, "Space member metadata") - original_metadata = as_mapping(original[name], "original Space member metadata") - digest, size = metadata.get("sha256"), metadata.get("bytes") - if (not isinstance(digest, str) or not SHA.fullmatch(digest) or type(size) is not int - or not 1 <= size <= MAX_FILE or original_metadata != {"sha256": digest, "bytes": size} - or metadata.get("object") != f"objects/sha256/{digest[:2]}/{digest}"): - raise ValueError("Space member identity mismatch") - path = root.joinpath(*name.split("/")) - if not path.is_file() or root not in path.resolve().parents or path.stat().st_size != size: - raise ValueError("Space member missing or wrong size") - if hashlib.sha256(path.read_bytes()).hexdigest() != digest: - raise ValueError("Space member digest mismatch") - corpus_path = root / "search_data.json.gz" - with gzip.open(corpus_path, "rb") as stream: - decoded = stream.read(MAX_EXPANDED + 1) - if len(decoded) > MAX_EXPANDED: - raise ValueError("expanded search corpus exceeds limit") - corpus = as_mapping(json.loads(decoded), "Space corpus") - rows = as_list(corpus.get("rc"), "Space corpus records") - if corpus.get("v") != 2 or len(rows) != manifest.get("record_count") or not rows: - raise ValueError("Space corpus record count mismatch") - # Index files are not allowed to silently degrade into an empty/rebuilt - # index when the selected generation is loaded by the actual application. - repos = as_list(corpus.get("rp"), "Space corpus repositories") - folders = as_list(corpus.get("fd"), "Space corpus folders") - if (not repos or any(not isinstance(repo, str) or not re.fullmatch(r"VoiceOfML/[A-Za-z0-9._-]+", repo) - for repo in repos)): - raise ValueError("invalid Space corpus repository dictionary") - repo_names = cast(list[str], repos) - if len(set(repo_names)) != len(repo_names) or len({repo.split("/")[-1] for repo in repo_names}) != len(repo_names): - raise ValueError("duplicate Space corpus repository") - folder_names: list[list[str]] = [] - for value in folders: - folder = as_list(value, "Space corpus folder") - if any(not isinstance(part, str) for part in folder): - raise ValueError("invalid Space corpus folder") - folder_names.append(cast(list[str], folder)) - digest_builder = hashlib.sha256() - # Bootstrap pages contain at most 500 rows; retain only those prefixes and - # counts rather than materializing another complete Python corpus. - repo_prefixes: dict[str, list[dict[str, object]]] = {repo: [] for repo in repo_names} - repo_counts = dict.fromkeys(repo_names, 0) - global_prefix: list[dict[str, object]] = [] - for row in rows: - item = as_list(row, "Space corpus record") - if (len(item) != 6 or type(item[0]) is not int or not 0 <= item[0] < len(repo_names) - or not isinstance(item[1], str) or not isinstance(item[2], str) or type(item[3]) is not int - or not 0 <= item[3] < len(folder_names) or type(item[5]) is not int or item[5] not in (0, 1)): - raise ValueError("invalid Space corpus record") - if not isinstance(item[4], (int, str)) or isinstance(item[4], bool): - raise ValueError("invalid Space corpus record size") - repo = repo_names[item[0]] - repo_counts[repo] += 1 - if len(global_prefix) < 500 or len(repo_prefixes[repo]) < 500: - record: dict[str, object] = {"Repo": repo, "File": item[1], "Extension": item[2], - "Folder": folder_names[item[3]], "Size": item[4], "HasTxt": bool(item[5])} - append_bootstrap_record(global_prefix, repo_prefixes[repo], record) - for text in (item[1], repo_names[item[0]], "/".join(folder_names[item[3]])): - digest_builder.update(text.lower().encode("utf-8")) - digest_builder.update(b"\0") - browser_roots = validate_directory_data(root, repo_names) - digest = digest_builder.digest() - words, _ = load_word_index(root / "search_words.bin.gz", len(rows), digest, materialize=False) - if not words: - raise ValueError("Space word index is missing, invalid or empty") - for width in (2, 3): - grams, _ = load_ngram_index(root / f"search_ngrams_{width}.bin.gz", width, len(rows), digest) - if not grams: - raise ValueError(f"Space {width}-gram index is missing, invalid or empty") - for family in ("initial", "sidebar"): - listing = read_json_mapping(root / family / "manifest.json", "Space bootstrap manifest") - urls = as_list(listing.get("urls"), "Space bootstrap URLs") - if not urls: - raise ValueError("invalid Space bootstrap manifest") - prefix = f"/data/{family}/" - listed: set[str] = set() - for url in urls: - if not isinstance(url, str) or not url.startswith(prefix): - raise ValueError("invalid Space bootstrap URL") - name = f"{family}/" + url[len(prefix):] - if not safe_name(name) or name not in entries or name in listed or name.endswith("/manifest.json"): - raise ValueError("missing or duplicated Space bootstrap member") - listed.add(name) - expected = {name for name in entries if name == f"{family}/global.json" - or name.startswith(f"{family}/repos/")} - wanted = {f"{family}/global.json"} | { - f"{family}/repos/{quote(repo.split('/')[-1], safe='')}.json" for repo in repo_names} - if listed != expected or listed != wanted: - raise ValueError("Space bootstrap manifest does not cover its members") - for repo in [None, *repo_names]: - name = "initial/global.json" if repo is None else f"initial/repos/{quote(repo.split('/')[-1], safe='')}.json" - payload = read_json_mapping(root / name, "Space initial payload") - expected_records = global_prefix if repo is None else repo_prefixes[repo] - expected_total = len(rows) if repo is None else repo_counts[repo] - page_size = payload.get("page_size") - if (payload.get("version") != 2 or payload.get("mode") != ("global" if repo is None else "repo") - or payload.get("repo") != repo or payload.get("sort") != "relevance" or payload.get("page") != 1 - or type(page_size) is not int or not 1 <= page_size <= 500 - or payload.get("total") != expected_total - or payload.get("results") != expected_records[:page_size]): - raise ValueError("Space initial payload does not match corpus") - sidebar = read_json_mapping(root / "sidebar/global.json", "Space sidebar payload") - repo_summaries = as_list(sidebar.get("repos"), "Space sidebar repositories") - expected_summaries = [{"name": repo, "count": repo_counts[repo]} for repo in sorted(repo_names)] - if repo_summaries != expected_summaries: - raise ValueError("Space sidebar repositories do not match corpus") - for repo in repo_names: - name = f"sidebar/repos/{quote(repo.split('/')[-1], safe='')}.json" - payload = read_json_mapping(root / name, "Space sidebar repository") - root_entry = browser_roots[repo] - if (payload.get("repo") != repo or payload.get("path") != "" - or payload.get("folders") != root_entry.get("d") - or payload.get("files") != root_entry.get("f")): - raise ValueError("invalid Space sidebar repository") - return SelectedGeneration(generation=generation, directory=root, file_count=len(entries), - record_count=len(rows)) +"""Compatibility import for backend.search.corpus.infrastructure.selection.""" +import sys +from backend.search.corpus.infrastructure import selection as _implementation +from backend.search.corpus.infrastructure.selection import ( + MANDATORY as MANDATORY, + MAX_EXPANDED as MAX_EXPANDED, + MAX_FILE as MAX_FILE, + MAX_FILES as MAX_FILES, + SHA as SHA, + SelectedGeneration as SelectedGeneration, + append_bootstrap_record as append_bootstrap_record, + as_list as as_list, + as_mapping as as_mapping, + canonical as canonical, + inspect_generation as inspect_generation, + read_compressed_mapping as read_compressed_mapping, + read_json_mapping as read_json_mapping, + safe_name as safe_name, + validate_directory_data as validate_directory_data, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_execution.py b/backend/search_execution.py index 6f2975fb47ac533e9ed336ec25a20c57737f8fba..a6345685d1be7be8901541626ca476015927d7c0 100644 --- a/backend/search_execution.py +++ b/backend/search_execution.py @@ -1,165 +1,13 @@ -"""One owned search thread; active work retains its slot until it exits.""" -import asyncio -from collections.abc import Callable -from concurrent.futures import ThreadPoolExecutor -import logging -import time -import threading -from types import TracebackType -from typing import TypeVar - - -logger = logging.getLogger(__name__) - -T = TypeVar("T") - - -class SearchCancelled(Exception): - """The requester left while a cooperative search was running.""" - - -class SearchBusy(Exception): - pass - - -_search_thread = threading.local() - - -def check_search_cancelled() -> None: - event = getattr(_search_thread, "cancelled", None) - if event is not None and event.is_set(): - raise SearchCancelled() - - -def _report_close_failure(task: asyncio.Task[None], state: dict[str, int | bool]) -> None: - if task.done() and not task.cancelled(): - error = task.exception() - if error is not None and not state["waiters"] and not state["observed"]: - state["observed"] = True - task.get_loop().call_exception_handler({ - "message": "SearchExecutor close failed without a waiting caller", - "exception": error, - "task": task, - }) - - -class SearchExecutor: - def __init__(self, capacity: int = 32) -> None: - self.capacity = capacity - self._pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="search") - self._lock = asyncio.Lock() - self._tasks: set[asyncio.Task[tuple[object, float, float]]] = set() - self._closing = False - self._close_task: asyncio.Task[None] | None = None - self._close_state: dict[str, int | bool] | None = None - self._foreground: set[asyncio.Task[tuple[object, float, float]]] = set() - - async def __aenter__(self) -> "SearchExecutor": - return self - - async def __aexit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, - traceback: TracebackType | None) -> None: - await self.close() - - async def run(self, function: Callable[[], T], *, background: bool = False) -> tuple[T, float, float]: - if self._closing or len(self._tasks) >= self.capacity: - raise SearchBusy() - job = {"started": False} - cancelled = threading.Event() - queued = time.perf_counter() - predecessors = tuple(self._foreground) if background else () - - def compute() -> tuple[T, float, float]: - started = time.perf_counter() - _search_thread.cancelled = cancelled - try: - check_search_cancelled() - result = function() - return result, (started - queued) * 1000, (time.perf_counter() - started) * 1000 - finally: - del _search_thread.cancelled - - async def execute() -> tuple[T, float, float]: - if predecessors: - await asyncio.wait(predecessors) - async with self._lock: - job["started"] = True - return await asyncio.get_running_loop().run_in_executor(self._pool, compute) - - task = asyncio.create_task(execute()) - self._tasks.add(task) - if not background: - self._foreground.add(task) - - def finished(done: asyncio.Task[tuple[T, float, float]]) -> None: - self._tasks.discard(done) - self._foreground.discard(done) - if not done.cancelled(): - done.exception() # Consume failures when the requester has left. - - task.add_done_callback(finished) - try: - return await asyncio.shield(task) - except asyncio.CancelledError: - cancelled.set() - if not job["started"]: - task.cancel() # Queued work has no side effects and can be dropped. - raise - - async def close(self) -> None: - if (self._close_task is None or - (self._close_task.done() and - (self._close_task.cancelled() or self._close_task.exception() is not None))): - self._closing = True - - async def drain() -> None: - await asyncio.gather(*self._tasks, return_exceptions=True) - loop = asyncio.get_running_loop() - joined = loop.create_future() - - def notify(error: BaseException | None) -> None: - if not joined.done(): - if error is None: - joined.set_result(None) - else: - joined.set_exception(error) - - def shutdown() -> None: - error = None - try: - self._pool.shutdown(wait=True) - except BaseException as exc: - error = exc - # Log in the worker: even a successfully queued callback may - # never run if the loop closes, or its future is cancelled. - logger.exception("SearchExecutor shutdown failed") - try: - loop.call_soon_threadsafe(notify, error) - except RuntimeError: - # The host must keep the loop alive until close completes. - pass - - threading.Thread(target=shutdown, name="search-shutdown").start() - await joined - - self._close_task = asyncio.create_task(drain()) - close_state: dict[str, int | bool] = {"waiters": 0, "observed": False} - self._close_state = close_state - - self._close_task.add_done_callback(lambda task: _report_close_failure(task, close_state)) - task = self._close_task - state = self._close_state - if state is None: - raise RuntimeError("SearchExecutor close state missing") - state["waiters"] += 1 - try: - # A cancelled caller must not cancel the drain or its owned jobs. - await asyncio.shield(task) - except asyncio.CancelledError: - raise - except BaseException: - state["observed"] = True - raise - finally: - state["waiters"] -= 1 - _report_close_failure(task, state) +"""Compatibility import for backend.search.infrastructure.executor.""" +import sys +from backend.search.infrastructure import executor as _implementation +from backend.search.infrastructure.executor import ( + SearchBusy as SearchBusy, + SearchCancelled as SearchCancelled, + SearchExecutor as SearchExecutor, + T as T, + check_search_cancelled as check_search_cancelled, + logger as logger, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_filters.py b/backend/search_filters.py index b0b8726969c6a6ebacb0769f70f18845cc34eff9..ff2561b3e6ded2926c46dfdc8de30829e58246ca 100644 --- a/backend/search_filters.py +++ b/backend/search_filters.py @@ -1,134 +1,14 @@ -"""Typed search record filters over a caller-owned corpus snapshot.""" -from __future__ import annotations - -from collections.abc import Iterable, Mapping, Sequence -from typing import cast - -SearchRecord = dict[str, object] -FolderIndex = Mapping[str, Mapping[str, Sequence[int]]] -RepoIndex = Mapping[str, Sequence[int]] - - -def score_record(record: SearchRecord, query_tokens: Iterable[str], search_folders: bool = True) -> int: - score = 0 - file_name = cast(str, record.get("_file_lower", "")) - repo = cast(str, record.get("_repo_lower", "")) - folder_text = cast(str, record.get("_folder_text", "")) - for token in query_tokens: - if token in file_name: - score += 3 - if search_folders and token in folder_text: - score += 2 - if token in repo: - score += 1 - return score - - -def apply_filters(records: Sequence[SearchRecord], indices: Iterable[int], repos: Sequence[str] | None = None, - extensions: Sequence[str] | None = None, folders: Sequence[str] | None = None, - min_size: int | float | None = None, max_size: int | float | None = None, - folder_match_mode: str = "prefix") -> list[int]: - repos_set = set(repos) if repos else None - extensions_lower = {extension.lower() for extension in extensions} if extensions else None - folder_set = {folder.strip("/") for folder in folders} if folders else None - if folder_match_mode != "exact" and folder_set and "" in folder_set: - # Unlike the Worker, an empty API prefix includes the complete scope. - folder_set = None - folder_prefix = next(iter(folder_set)) + "/" if folder_set and len(folder_set) == 1 and folder_match_mode != "exact" else None - result: list[int] = [] - for idx in indices: - record = records[idx] - if repos_set and record.get("Repo") not in repos_set: - continue - if extensions_lower and record.get("_ext_lower", "") not in extensions_lower: - continue - rec_path = "" - if folder_set: - rec_path = (cast(str, record["_folder_path"]) if "_folder_path" in record - else "/".join(cast(list[str], record.get("Folder", []) or []))) - matched = rec_path in folder_set - if not matched and folder_match_mode != "exact": - if folder_prefix is not None: - matched = rec_path.startswith(folder_prefix) - else: - end = rec_path.rfind("/") - while end > 0: - if rec_path[:end] in folder_set: - matched = True - break - end = rec_path.rfind("/", 0, end) - if not matched: - continue - size = record.get("Size") - if size and isinstance(size, (int, float)) and size > 0: - if min_size is not None and size < min_size: - continue - if max_size is not None and size > max_size: - continue - result.append(idx) - return result - - -def apply_mixed_folder_filters(records: Sequence[SearchRecord], indices: Sequence[int], - self_folders: Sequence[str] | None = None, - subtree_folders: Sequence[str] | None = None) -> Sequence[int]: - self_set = {str(path).strip("/") for path in (self_folders or [])} - subtree_set = {str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/")} - if not self_set and not subtree_set: - return indices - result: list[int] = [] - for idx in indices: - rec_folders = cast(list[str], records[idx].get("Folder", []) or []) - rec_path = "/".join(rec_folders) - if rec_path in self_set: - result.append(idx) - continue - if not subtree_set: - continue - if rec_path in subtree_set: - result.append(idx) - continue - matched = False - prefix = "" - for depth, part in enumerate(rec_folders): - # A slash may itself be part of a folder component; only actual - # component boundaries are eligible subtree matches. - prefix = part if depth == 0 else prefix + "/" + part - if prefix in subtree_set: - matched = True - break - if matched: - result.append(idx) - return result - - -def mixed_folder_index_candidates(records: Sequence[SearchRecord], folder_index: FolderIndex, - repo_records_map: RepoIndex, repos: Sequence[str] | None, - self_folders: Sequence[str] | None = None, - subtree_folders: Sequence[str] | None = None) -> list[int] | None: - """Return a bounded corpus-ordered superset, or None to retain a full scan.""" - if len(self_folders or ()) + len(subtree_folders or ()) > 64: - return None - paths = {str(path).strip("/") for path in (self_folders or [])} - paths.update(str(path).strip("/") for path in (subtree_folders or []) if str(path).strip("/")) - if not paths: - return None - selected_repos = sorted(set(repos)) if repos else list(repo_records_map) - scope_size = sum(len(repo_records_map.get(repo, ())) for repo in selected_repos) if repos else len(records) - # Broad selections fall back rather than allocating an unbounded set. - limit = min(32768, max(64, scope_size // 2)) - postings: list[Sequence[int]] = [] - estimated = 0 - for repo in selected_repos: - folders = folder_index.get(repo, {}) - for path in paths: - indices = folders.get(path, ()) - estimated += len(indices) - if estimated > limit: - return None - if indices: - postings.append(indices) - candidates: set[int] = set() - for indices in postings: - candidates.update(indices) - return sorted(candidates) +"""Compatibility import for backend.search.domain.filters.""" +import sys +from backend.search.domain import filters as _implementation +from backend.search.domain.filters import ( + FolderIndex as FolderIndex, + RepoIndex as RepoIndex, + SearchRecord as SearchRecord, + apply_filters as apply_filters, + apply_mixed_folder_filters as apply_mixed_folder_filters, + mixed_folder_index_candidates as mixed_folder_index_candidates, + score_record as score_record, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_indexes.py b/backend/search_indexes.py index 84c3492e3370b565d648d89044a951862594c4e4..59cf1310ba8924f1db2febcfb43e5ce73b10a0bd 100644 --- a/backend/search_indexes.py +++ b/backend/search_indexes.py @@ -1,205 +1,18 @@ -"""Readers for the generated word and n-gram posting files. - -The generated formats are deliberately small and self-describing. Keeping -their parsing independent from the FastAPI application makes malformed input -handling testable without importing application state. -""" - -import gzip -from collections.abc import Iterator -from pathlib import Path -from typing import Literal, overload - -try: - import _search_index_native as _native_index -except ImportError: - _native_index = None - -_native_read_entries = getattr(_native_index, "read_entries", None) -_native_decode_postings = getattr(_native_index, "decode_postings", None) - - -NGRAM_MAGIC = b"VNG3" -WORD_INDEX_MAGIC = b"VWI2" -WORD_INDEX_TOKENIZER = "jieba-0.42.1-cjk-char-v1" - -PostingLocation = tuple[int, int, int] -Posting = set[int] | PostingLocation -PostingIndex = dict[str, Posting] - - -def decode_varint(data: bytes, offset: int) -> tuple[int, int]: - value = 0 - shift = 0 - while offset < len(data): - byte = data[offset] - offset += 1 - value |= (byte & 0x7F) << shift - if not byte & 0x80: - return value, offset - shift += 7 - raise ValueError("truncated varint") - - -def decode_postings(data: bytes | memoryview, record_count: int | None = None) -> set[int]: - # Non-byte, strided, or mutable-backed buffers retain Python iteration semantics. - if (_native_decode_postings is not None and record_count is None and - (type(data) is bytes or (type(data) is memoryview and data.readonly and - type(data.obj) is bytes and data.format == "B" and - data.ndim == 1 and data.c_contiguous))): - try: - return _native_decode_postings(data) - except OverflowError: - # Python integers support valid varints and cumulative IDs wider than 64 bits. - pass - return _decode_postings_python(data, record_count) - - -def _decode_postings_python(data: bytes | memoryview, record_count: int | None = None) -> set[int]: - record_ids: set[int] = set() - previous = 0 - value = shift = 0 - for byte in data: - value |= (byte & 0x7F) << shift - if byte & 0x80: - shift += 7 - continue - previous += value - if record_count is not None and previous >= record_count: - raise ValueError("posting record id out of range") - record_ids.add(previous) - value = shift = 0 - if shift: - raise ValueError("truncated varint") - return record_ids - - -def _bounded_slice(data: bytes, offset: int, length: int) -> tuple[int, int]: - end = offset + length - if length < 0 or end < offset or end > len(data): - raise ValueError("truncated postings") - return offset, end - - -def _validate_postings(data: bytes, start: int, end: int, record_count: int) -> int: - """Count distinct monotonic IDs without allocating a temporary posting set.""" - previous = 0 - last = -1 - count = 0 - value = shift = 0 - for offset in range(start, end): - byte = data[offset] - value |= (byte & 0x7F) << shift - if byte & 0x80: - shift += 7 - continue - previous += value - if previous >= record_count: - raise ValueError("posting record id out of range") - if previous != last: - count += 1 - last = previous - value = shift = 0 - if shift: - raise ValueError("truncated varint") - return count - - -def _read_posting_entries(data: bytes, offset: int, count: int, record_count: int, - materialize: bool = True) -> Iterator[tuple[str, PostingLocation, set[int] | None]]: - """Yield validated entries while leaving storage policy to each loader.""" - for _ in range(count): - key_length, offset = decode_varint(data, offset) - key_start, offset = _bounded_slice(data, offset, key_length) - key = data[key_start:offset].decode("utf-8") - posting_count, offset = decode_varint(data, offset) - posting_length, offset = decode_varint(data, offset) - posting_start, offset = _bounded_slice(data, offset, posting_length) - decoded = decode_postings(memoryview(data)[posting_start:offset], record_count) if materialize else None - actual_count = len(decoded) if decoded is not None else _validate_postings(data, posting_start, offset, record_count) - if actual_count != posting_count: - raise ValueError("posting count mismatch") - yield key, (posting_start, offset, posting_count), decoded - if offset != len(data): - raise ValueError("trailing postings") - - -def _load_posting_entries(data: bytes, offset: int, count: int, record_count: int, - materialize: bool) -> PostingIndex: - if _native_read_entries is not None: - try: - return _native_read_entries(data, offset, count, record_count, materialize) - except OverflowError: - # Retain arbitrary-width varint behavior for unusual valid inputs. - pass - if materialize: - entries: PostingIndex = {} - for key, _, decoded in _read_posting_entries(data, offset, count, record_count, True): - if decoded is None: - raise RuntimeError("materialized posting missing") - entries[key] = decoded - return entries - return {key: location for key, location, _ in _read_posting_entries(data, offset, count, record_count, False)} - - -def load_ngram_index( - path: Path, - width: int, - record_count: int, - expected_digest: bytes, -) -> tuple[PostingIndex, bytes]: - try: - data = gzip.decompress(path.read_bytes()) - if not data.startswith(NGRAM_MAGIC) or len(data) < 37 or data[4] != width: - return {}, b"" - if data[5:37] != expected_digest: - return {}, b"" - offset = 37 - stored_record_count, offset = decode_varint(data, offset) - count, offset = decode_varint(data, offset) - if stored_record_count != record_count: - return {}, b"" - postings = _load_posting_entries(data, offset, count, record_count, False) - return postings, data - except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError): - return {}, b"" - - -@overload -def load_word_index(path: Path, record_count: int, expected_digest: bytes, - materialize: Literal[False]) -> tuple[PostingIndex, bytes]: ... - - -@overload -def load_word_index(path: Path, record_count: int, expected_digest: bytes, - materialize: Literal[True] = True) -> PostingIndex: ... - - -def load_word_index(path: Path, record_count: int, expected_digest: bytes, - materialize: bool = True) -> PostingIndex | tuple[PostingIndex, bytes]: - try: - data = gzip.decompress(path.read_bytes()) - if not data.startswith(WORD_INDEX_MAGIC): - return {} if materialize else ({}, b"") - offset = len(WORD_INDEX_MAGIC) - tokenizer_length, offset = decode_varint(data, offset) - tokenizer_start, offset = _bounded_slice(data, offset, tokenizer_length) - tokenizer = data[tokenizer_start:offset].decode("utf-8") - digest_start, offset = _bounded_slice(data, offset, 32) - if tokenizer != WORD_INDEX_TOKENIZER or data[digest_start:offset] != expected_digest: - return {} if materialize else ({}, b"") - stored_record_count, offset = decode_varint(data, offset) - count, offset = decode_varint(data, offset) - if stored_record_count != record_count: - return {} if materialize else ({}, b"") - entries = _load_posting_entries(data, offset, count, record_count, materialize) - return entries if materialize else (entries, data) - except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError): - return {} if materialize else ({}, b"") - - -def resolve_postings(value: Posting | frozenset[int] | bytes | memoryview, buffer: bytes) -> set[int]: - if isinstance(value, tuple): - start, end, _ = value - return decode_postings(memoryview(buffer)[start:end]) - return set(value) if isinstance(value, (set, frozenset)) else decode_postings(value) +"""Compatibility import for backend.search.corpus.infrastructure.indexes.""" +import sys +from backend.search.corpus.infrastructure import indexes as _implementation +from backend.search.corpus.infrastructure.indexes import ( + NGRAM_MAGIC as NGRAM_MAGIC, + Posting as Posting, + PostingIndex as PostingIndex, + PostingLocation as PostingLocation, + WORD_INDEX_MAGIC as WORD_INDEX_MAGIC, + WORD_INDEX_TOKENIZER as WORD_INDEX_TOKENIZER, + decode_postings as decode_postings, + decode_varint as decode_varint, + load_ngram_index as load_ngram_index, + load_word_index as load_word_index, + resolve_postings as resolve_postings, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_matching.py b/backend/search_matching.py index 652ecdc999df3790981be62641db86494f1d2bb3..6fce5af9ab86e1b3018b47b0fca81b3b8e50c4fd 100644 --- a/backend/search_matching.py +++ b/backend/search_matching.py @@ -1,179 +1,14 @@ -"""Bounded exact, wildcard and fuzzy search matching.""" -from collections.abc import Callable -import re - - -def compile_exact_matcher(query: str) -> Callable[[str], bool]: - if "*" not in query and "?" not in query: - lower = query.lower() - return lambda text: lower in text.lower() - if not query.strip("*"): - # An unanchored sequence of stars matches the empty substring. - return lambda _text: True - if "*" in query and "?" in query and not query.strip("*?"): - # Stars may match nothing; each question consumes a non-LF code point. - required = query.count("?") - - def matches_question_run(text: str) -> bool: - start = 0 - while start < len(text): - end = text.find("\n", start) - if end < 0: - end = len(text) - if end - start >= required: - return True - start = max(start, end) + 1 - return False - - return matches_question_run - if "*" not in query: - # Escaped fixed-width literals and dots need no variable-length regex - # repetition, retaining IGNORECASE and dot's LF behavior. - fixed = re.compile("".join("." if char == "?" else re.escape(char) for char in query), re.IGNORECASE) - if len(query) < 128 or not any(char != "?" for char in query): - return lambda text: fixed.search(text) is not None - literals = [re.compile(re.escape(char), re.IGNORECASE) - for char in dict.fromkeys(query) if char != "?"] - return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals)) - and fixed.search(text) is not None) - # In substring matching, stars at either boundary can match zero chars. - # Keep Unicode IGNORECASE behavior, unlike the literal .lower() branch. - core = query.strip("*") - if core and "*" not in core and "?" not in core: - literal = re.compile(re.escape(core), re.IGNORECASE) - return lambda text: literal.search(text) is not None - if "*" in core and "?" not in core and "\n" not in core: - # A leftmost match for each mandatory chunk leaves the most room for - # later chunks. Wildcard dots cannot cross LF in Python's regex rules. - chunks = [re.compile(re.escape(part), re.IGNORECASE) - for part in re.split(r"\*+", core)] - - def matches_chunks(text: str) -> bool: - for line in text.split("\n"): - position = 0 - for chunk in chunks: - match = chunk.search(line, position) - if match is None: - break - position = match.end() - else: - return True - return False - - return matches_chunks - # A leading/trailing wildcard run followed/preceded by a fixed literal - # has only one variable-width part. Strip its boundary stars: they can - # always match zero characters in an unanchored search. The remaining - # questions have fixed width and therefore cannot backtrack exponentially. - core_parts = core.split("*") - nonempty_parts = [part for part in core_parts if part] - if len(nonempty_parts) == 2: - first, last = nonempty_parts - first_questions = first and not first.strip("?") and "?" not in last - last_questions = last and not last.strip("?") and "?" not in first - if first_questions or last_questions: - fixed = first + last - expression = re.compile("".join("." if char == "?" else re.escape(char) for char in fixed), re.IGNORECASE) - if len(fixed) >= 128: - literals = [re.compile(re.escape(char), re.IGNORECASE) - for char in dict.fromkeys(fixed) if char != "?"] - return lambda text: ((len(text) <= 4096 or all(literal.search(text) for literal in literals)) - and expression.search(text) is not None) - return lambda text: expression.search(text) is not None - # Bitset NFA: each bit is a pattern position. Collapse adjacent stars so - # epsilon closure needs one shift. No input can cause regex backtracking. - pattern = re.sub(r"\*+", "*", query) - stars = questions = 0 - literal_bits: dict[str, int] = {} - for index, char in enumerate(pattern): - bit = 1 << index - if char == "*": - stars |= bit - elif char == "?": - questions |= bit - else: - literal_bits[char] = literal_bits.get(char, 0) | bit - # Single-character regexes retain Python IGNORECASE's Unicode semantics. - literals = [(re.compile(re.escape(char), re.IGNORECASE), bits) - for char, bits in literal_bits.items()] - masks: dict[str, int] = {} - end = 1 << len(pattern) - start = 1 | ((1 & stars) << 1) - - def matches(text: str) -> bool: - # Every literal is mandatory; C-level scans reject unrelated fields early. - if any(regex.search(text) is None for regex, _ in literals): - return False - active = start - for char in text: - mask = masks.get(char) - if mask is None: - mask = sum(bits for regex, bits in literals if regex.fullmatch(char)) - if len(masks) >= 512: - masks.clear() - masks[char] = mask - wildcard = char != "\n" - active = ((active & (mask | (questions if wildcard else 0))) << 1) | ( - active & stars if wildcard else 0) | 1 - active |= (active & stars) << 1 - if active & end: - return True - return False - return matches - - -def matches_exact_query(text: str, query: str) -> bool: - return compile_exact_matcher(query)(text) - - -def split_exact_terms(query: str) -> list[str]: - """Whitespace separates literal terms; each term must match independently.""" - return [term for term in query.split() if term] - -def edit_distance(s1: str, s2: str, max_dist: int = 2) -> int: - if abs(len(s1) - len(s2)) > max_dist: - return 999 - prev = list(range(len(s2) + 1)) - for i, c1 in enumerate(s1): - curr = [i + 1] - for j, c2 in enumerate(s2): - cost = 0 if c1 == c2 else 1 - curr.append(min(prev[j + 1] + 1, curr[j] + 1, prev[j] + cost)) - if min(curr) > max_dist: - return 999 - prev = curr - return prev[-1] - -def could_be_fuzzy(tok: str, word: str, max_dist: int = 2) -> bool: - if abs(len(tok) - len(word)) > max_dist: - return False - if len(tok) < 4: - return True - counts: dict[str, int] = {} - for ch in tok: - counts[ch] = counts.get(ch, 0) + 1 - diff = 0 - for ch in word: - if counts.get(ch, 0) > 0: - counts[ch] -= 1 - else: - diff += 1 - if diff > 2 * max_dist: - return False - for remaining in counts.values(): - diff += remaining - if diff > 2 * max_dist: - return False - return True - - -def fuzzy_distance_budget(token: str) -> int: - """Short tokens cannot tolerate the same edit radius as longer words.""" - if len(token) <= 1: - return 0 - return 1 if len(token) <= 3 else 2 - - -def is_fuzzy_match(token: str, word: str) -> bool: - limit = fuzzy_distance_budget(token) - return could_be_fuzzy(token, word, limit) and edit_distance(token, word, max_dist=limit) <= limit +"""Compatibility import for backend.search.domain.matching.""" +import sys +from backend.search.domain import matching as _implementation +from backend.search.domain.matching import ( + compile_exact_matcher as compile_exact_matcher, + could_be_fuzzy as could_be_fuzzy, + edit_distance as edit_distance, + fuzzy_distance_budget as fuzzy_distance_budget, + is_fuzzy_match as is_fuzzy_match, + matches_exact_query as matches_exact_query, + split_exact_terms as split_exact_terms, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_runtime_entry.py b/backend/search_runtime_entry.py index d5d0be9f7f1cd6f5078a7ebfe8c1bc93cb66dcf5..906f94e65516d3529242259b2c90c964c18fbf46 100644 --- a/backend/search_runtime_entry.py +++ b/backend/search_runtime_entry.py @@ -1,73 +1,9 @@ -"""Optional Uvicorn entry point selecting a verified Space search generation. - -Without configuration the original ASGI application is used unchanged. If a -candidate is configured, its complete file set and index structure are checked -before the application starts. A failed candidate stops startup and never mixes -files with the bundled fallback. The original ASGI generation identifier remains -unchanged; the independent health endpoint reports the selected bucket identity. -""" -from __future__ import annotations - -import json -import os -from collections.abc import AsyncGenerator, Awaitable, Callable -from contextlib import asynccontextmanager -from pathlib import Path - -from fastapi import FastAPI, Request -from fastapi.responses import JSONResponse, Response - -from .search_data_selector import inspect_generation - - -def selected_app() -> FastAPI: - generation = os.environ.get("SEARCH_DATA_GENERATION", "") - directory = os.environ.get("SEARCH_DATA_DIRECTORY", "") - if bool(generation) != bool(directory): - raise RuntimeError("SEARCH_DATA_GENERATION and SEARCH_DATA_DIRECTORY must be set together") - selected = inspect_generation(Path(directory), generation) if generation else None - from . import app as service - if selected is None: - return service.app - root = selected.directory - service.DATA_PATH = root / "search_data.json.gz" - service.NGRAM_PATHS = {2: root / "search_ngrams_2.bin.gz", 3: root / "search_ngrams_3.bin.gz"} - service.WORD_INDEX_PATH = root / "search_words.bin.gz" - service.FOLDER_TREE_PATH = root / "folder_tree.json.gz" - service.FOLDER_BROWSER_PATH = root / "folder_browser.json.gz" - service.SIDEBAR_DATA_PATH = root / "sidebar" - original_lifespan = service.app.router.lifespan_context - - @asynccontextmanager - async def verified_lifespan(application: FastAPI) -> AsyncGenerator[None, None]: - async with original_lifespan(application): - if (len(service.records) != selected.record_count or not service.word_index - or not service.ngram_postings.get(2) or not service.ngram_postings.get(3)): - raise RuntimeError("selected search generation did not load completely") - application.state.selected_search_generation = selected.generation - application.state.selected_search_files = selected.file_count - application.state.selected_search_records = len(service.records) - print(json.dumps({"kind": "search-generation-loaded", "generation": selected.generation, - "surface": "space", "files_verified": selected.file_count, - "records_loaded": len(service.records), "api_generation": service.search_generation()}), - flush=True) - yield - - service.app.router.lifespan_context = verified_lifespan - - @service.app.middleware("http") - async def generation_status(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response: - if request.url.path == "/api/search-data-generation": - current = getattr(request.app.state, "selected_search_generation", None) - if current != selected.generation: - return JSONResponse({"error": "generation not loaded"}, status_code=503) - return JSONResponse({"generation": current, "surface": "space", "verified": True, - "files": selected.file_count, "records": len(service.records), - "api_generation": service.search_generation()}, - headers={"Cache-Control": "no-store"}) - return await call_next(request) - - return service.app - - -app = selected_app() +"""Compatibility import for backend.search.infrastructure.runtime_entry.""" +import sys +from backend.search.infrastructure import runtime_entry as _implementation +from backend.search.infrastructure.runtime_entry import ( + app as app, + selected_app as selected_app, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_term_candidates.py b/backend/search_term_candidates.py index e71320819bb677f45aa4d3918d75e601ad0fa677..208f42c38eba94967fe0aca37f05694915593326 100644 --- a/backend/search_term_candidates.py +++ b/backend/search_term_candidates.py @@ -1,129 +1,10 @@ -"""Word and fuzzy candidate selection for a single search term.""" -from __future__ import annotations - -from collections.abc import Callable, Mapping, Sequence -from typing import cast - -from backend.search_execution import check_search_cancelled - -SearchRecord = dict[str, object] - - -def term_candidates(term: str, query_token_count: int, posting_cache: dict[str, set[int]], - search_folders: bool, *, tokenize: Callable[[str], list[str]], - scoped_word_postings: Callable[[str, bool], set[int]], - get_word_index: Callable[[], Mapping[str, object]], - get_records: Callable[[], Sequence[SearchRecord]], - get_vocab: Callable[[], Mapping[int, list[str]]], - is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]: - """Intersect term postings without truncating before record filters.""" - query_tokens = tokenize(term) - return candidates_for_tokens(query_tokens, query_token_count, posting_cache, search_folders, - tokenize=tokenize, scoped_word_postings=scoped_word_postings, - get_word_index=get_word_index, get_records=get_records, get_vocab=get_vocab, - is_fuzzy_match=is_fuzzy_match) - - -def candidates_for_tokens(query_tokens: Sequence[str], query_token_count: int, posting_cache: dict[str, set[int]], - search_folders: bool, *, tokenize: Callable[[str], list[str]], - scoped_word_postings: Callable[[str, bool], set[int]], - get_word_index: Callable[[], Mapping[str, object]], - get_records: Callable[[], Sequence[SearchRecord]], - get_vocab: Callable[[], Mapping[int, list[str]]], - is_fuzzy_match: Callable[[str, str], bool]) -> tuple[set[int], set[str]]: - """Resolve already-tokenized input without repeating tokenization.""" - # Candidate caps before repository and record filtering can lose valid hits. - fuzzy_candidate_limit = None - fuzzy_tokens: set[str] = set() - - def query_postings(token: str) -> set[int]: - if token not in posting_cache: - posting_cache[token] = scoped_word_postings(token, search_folders) - return posting_cache[token] - - exact_constraint = _exact_constraint(query_tokens, get_word_index, query_postings) - token_candidates: list[set[int]] = [] - for tok in query_tokens: - check_search_cancelled() - candidates: set[int] = query_postings(tok) if tok in get_word_index() else set() - if not candidates: - fuzzy_tokens.add(tok) - candidates = _fuzzy_candidates(tok, exact_constraint, fuzzy_candidate_limit, search_folders, - get_records, get_vocab, tokenize, is_fuzzy_match, query_postings) - if not candidates: - return set(), fuzzy_tokens - token_candidates.append(candidates) - return _intersect_candidates(token_candidates), fuzzy_tokens - - -def _exact_constraint(query_tokens: Sequence[str], get_word_index: Callable[[], Mapping[str, object]], - query_postings: Callable[[str], set[int]]) -> set[int] | None: - exact_constraint: set[int] | None = None - for tok in query_tokens: - if tok not in get_word_index(): - continue - postings = query_postings(tok) - if not postings: - continue - exact_constraint = set(postings) if exact_constraint is None else exact_constraint.intersection(postings) - return exact_constraint - - -def _intersect_candidates(token_candidates: list[set[int]]) -> set[int]: - if not token_candidates: - return set() - token_candidates.sort(key=len) - matched = set(token_candidates[0]) - for candidates in token_candidates[1:]: - matched.intersection_update(candidates) - if not matched: - break - return matched - - -def _fuzzy_candidates(tok: str, exact_constraint: set[int] | None, limit: int | None, search_folders: bool, - get_records: Callable[[], Sequence[SearchRecord]], - get_vocab: Callable[[], Mapping[int, list[str]]], tokenize: Callable[[str], list[str]], - is_fuzzy_match: Callable[[str, str], bool], - query_postings: Callable[[str], set[int]]) -> set[int]: - if exact_constraint is not None: - return _fuzzy_record_candidates(tok, exact_constraint, limit, search_folders, - get_records, tokenize, is_fuzzy_match) - return _fuzzy_vocabulary_candidates(tok, limit, get_vocab, is_fuzzy_match, query_postings) - - -def _fuzzy_record_candidates(tok: str, exact_constraint: set[int], limit: int | None, search_folders: bool, - get_records: Callable[[], Sequence[SearchRecord]], - tokenize: Callable[[str], list[str]], - is_fuzzy_match: Callable[[str, str], bool]) -> set[int]: - candidates: set[int] = set() - for offset, idx in enumerate(sorted(exact_constraint)): - if offset % 256 == 0: - check_search_cancelled() - rec = get_records()[idx] - record_tokens = tokenize(" ".join([cast(str, rec.get("File", "")), - *(cast(list[str], rec.get("Folder", []) or []) if search_folders else [])])) - if any(is_fuzzy_match(tok, word) for word in record_tokens): - candidates.add(idx) - if limit is not None and len(candidates) >= limit: - break - return candidates - - -def _fuzzy_vocabulary_candidates(tok: str, limit: int | None, - get_vocab: Callable[[], Mapping[int, list[str]]], - is_fuzzy_match: Callable[[str, str], bool], - query_postings: Callable[[str], set[int]]) -> set[int]: - candidates: set[int] = set() - tok_len = len(tok) - for delta in (-2, -1, 0, 1, 2): - for offset, vocab_word in enumerate(get_vocab().get(tok_len + delta, [])): - if offset % 256 == 0: - check_search_cancelled() - if is_fuzzy_match(tok, vocab_word): - candidates.update(query_postings(vocab_word)) - if limit is not None and len(candidates) >= limit: - break - if limit is not None and len(candidates) >= limit: - break - return candidates +"""Compatibility import for backend.search.domain.term_candidates.""" +import sys +from backend.search.domain import term_candidates as _implementation +from backend.search.domain.term_candidates import ( + SearchRecord as SearchRecord, + candidates_for_tokens as candidates_for_tokens, + term_candidates as term_candidates, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_transport.py b/backend/search_transport.py index 8ab1fddc1f614dadbd52247f9c935e2e53ea9478..d2038fc82834600826ae012b119d82a8a2552ad5 100644 --- a/backend/search_transport.py +++ b/backend/search_transport.py @@ -1,64 +1,10 @@ -"""Bound search uploads before JSON parsing; leave application failures untouched.""" -import asyncio - -from starlette.responses import Response -from starlette.types import ASGIApp, Message, Receive, Scope, Send - -SEARCH_BODY_MAX_BYTES = 8 * 1024 * 1024 -SEARCH_BODY_TIMEOUT_SECONDS = 15.0 - - -class SearchBodyLimitMiddleware: - def __init__(self, app: ASGIApp) -> None: - self.app = app - - async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - path = scope.get("path", "") - if (scope["type"] != "http" or scope["method"] != "POST" - or not (path == "/api/search" or path.startswith("/api/search/"))): - await self.app(scope, receive, send) - return - # Count actual wire bytes, including chunked uploads and misleading - # Content-Length. A bytearray also bounds overhead from tiny chunks. - body = bytearray() - status = None - chunk = b"" - message: Message = {} - deadline = asyncio.timeout(SEARCH_BODY_TIMEOUT_SECONDS) - try: - async with deadline: - while True: - message = await receive() - if message["type"] == "http.disconnect": - status = 204 - break - chunk = message.get("body", b"") - if len(body) + len(chunk) > SEARCH_BODY_MAX_BYTES: - status = 413 - break - body.extend(chunk) - if not message.get("more_body", False): - break - # receive may complete synchronously for buffered messages. - await asyncio.sleep(0) - except TimeoutError: - if not deadline.expired(): - raise - status = 408 - del message, chunk - if status is not None: - body.clear() - await Response(status_code=status, headers={"Cache-Control": "no-store"})(scope, receive, send) - return - buffered: bytes | None = bytes(body) - body.clear() - - async def replay() -> Message: - nonlocal buffered - if buffered is not None: - payload, buffered = buffered, None - return {"type": "http.request", "body": payload, "more_body": False} - return await receive() - - # The upload deadline ends before validation, routing or response send. - await self.app(scope, replay, send) +"""Compatibility import for backend.search.http.body_limit.""" +import sys +from backend.search.http import body_limit as _implementation +from backend.search.http.body_limit import ( + SEARCH_BODY_MAX_BYTES as SEARCH_BODY_MAX_BYTES, + SEARCH_BODY_TIMEOUT_SECONDS as SEARCH_BODY_TIMEOUT_SECONDS, + SearchBodyLimitMiddleware as SearchBodyLimitMiddleware, +) + +sys.modules[__name__] = _implementation diff --git a/backend/search_words.py b/backend/search_words.py index 8b3ebd3c3aa19a90e22be472e9064d7c36faf23f..1a28a13c13a42c27f28ddc04a8c2893fe69715a3 100644 --- a/backend/search_words.py +++ b/backend/search_words.py @@ -1,65 +1,13 @@ -"""Pure search token matching and word-index construction.""" -from collections.abc import Callable, Iterable, Mapping, Sequence -import hashlib -import re -from typing import cast - - -def records_digest(records: Sequence[Mapping[str, object]]) -> bytes: - digest = hashlib.sha256() - for record in records: - for value in (record.get("_file_lower", ""), record.get("_repo_lower", ""), - record.get("_folder_path_lower", "")): - digest.update(cast(str, value).encode("utf-8")) - digest.update(b"\0") - return digest.digest() - - -def tokenize(text: str, segment: Callable[[str], list[str]]) -> list[str]: - tokens: list[str] = [] - text_lower = text.lower() - tokens.extend(re.findall(r"[a-z0-9]+", text_lower)) - chinese_text = re.sub(r"[a-z0-9\s]+", " ", text_lower) - chinese_text = re.sub(r"[^\u4e00-\u9fff\u3400-\u4dbf\s]+", " ", chinese_text) - chinese_tokens = segment(chinese_text) - tokens.extend([token.strip() for token in chinese_tokens if token.strip()]) - chinese_token_set = set(chinese_tokens) - for ch in text_lower: - if "\u4e00" <= ch <= "\u9fff" or "\u3400" <= ch <= "\u4dbf": - if ch not in chinese_token_set: - tokens.append(ch) - # Stable token order keeps rebuilt vocabularies reproducible across hash seeds. - return list(dict.fromkeys(tokens)) - - -def matches_file_token(record: Mapping[str, object], token: str) -> bool: - return (token in cast(str, record.get("_full_file_lower", record.get("_file_lower", ""))) - or token in cast(str, record.get("_repo_lower", ""))) - - -def matches_file_query(record: Mapping[str, object], tokens: Iterable[str], fuzzy_tokens: set[str], *, - tokenize_text: Callable[[str], list[str]], - file_match: Callable[[Mapping[str, object], str], bool], - fuzzy_match: Callable[[str, str], bool]) -> bool: - file_tokens = tokenize_text(cast(str, record.get("_full_file_lower", record.get("_file_lower", "")))) if fuzzy_tokens else [] - return all(file_match(record, token) or ( - token in fuzzy_tokens and any(fuzzy_match(token, word) for word in file_tokens) - ) for token in tokens) - - -def build_vocab_by_len(words: Iterable[str], vocab: dict[int, list[str]]) -> None: - for word in words: - vocab.setdefault(len(word), []).append(word) - # Generated postings are sorted by term; rebuilt indexes must traverse the - # same vocabulary regardless of insertion order or Python hash seed. - for bucket in vocab.values(): - bucket.sort() - - -def build_word_index(records: Sequence[Mapping[str, object]], index: dict[str, set[int]], - tokenize_text: Callable[[str], list[str]]) -> None: - for idx, record in enumerate(records): - file_name = cast(str, record.get("File", "")) - folders = cast(list[str], record.get("Folder", [])) - for token in tokenize_text(" ".join([file_name] + folders)): - index.setdefault(token, set()).add(idx) +"""Compatibility import for backend.search.corpus.domain.words.""" +import sys +from backend.search.corpus.domain import words as _implementation +from backend.search.corpus.domain.words import ( + build_vocab_by_len as build_vocab_by_len, + build_word_index as build_word_index, + matches_file_query as matches_file_query, + matches_file_token as matches_file_token, + records_digest as records_digest, + tokenize as tokenize, +) + +sys.modules[__name__] = _implementation diff --git a/backend/seo.py b/backend/seo.py index 3fbad78afdb14a1bbd8f6fb4beb7b19d67e2aba6..c0dbca65e73a4856cae5e2129c172952d265b872 100644 --- a/backend/seo.py +++ b/backend/seo.py @@ -1,317 +1,27 @@ -"""Small, deterministic metadata catalog; no source-body downloads or search changes. - -The same file is copied to Pages' scripts/build/seo.py. Pages owns the indexable -catalog; new HF catalog pages are noindex mirrors because HF appends a Hub canonical. -""" -from __future__ import annotations - -import argparse -from collections import Counter, defaultdict -import gzip -import hashlib -from html import escape -import json -from pathlib import Path -import re -from typing import TypedDict, cast -from urllib.parse import quote, urlencode - - -class CatalogRecord(TypedDict): - Repo: str - File: str - Extension: str - Folder: list[str] - Size: object - - -class Pilot(TypedDict): - samples: list[list[str]] - folder: list[str] - - -class CatalogResult(TypedDict): - files: dict[str, str] - manifest: dict[str, object] - - -PAGES = "https://vomebook.github.io/search/" -HF = "https://voiceofml-search.hf.space/" -DESCRIPTION = "检索 VoiceOfML 公开资料的文件名、路径和格式,浏览文库目录,在线阅读或下载原始文件。" -PILOT: Pilot = { - "samples": [ - ["VoiceOfML/VOMEBOOK", "马列之声ebook小组第二批成果集成赞助部分/jiang/中国社会主义时代的教育革命 研究资料集成pdf(近800种)/工农兵大学生/工农兵学员的优秀代表----曹谊林.txt"], - ["VoiceOfML/SovMaterials", "重要中文文献/斯大林著作各种/斯大林语录.txt"], - ["VoiceOfML/GPCREducation", "化学/简明化学手册.pdf"], - ["VoiceOfML/Teachers", "其他/李达/李达传记.pdf"], - ["VoiceOfML/MLMRL-Library", "历史/中国近代史1.pdf"], - ["VoiceOfML/Japanese-Materials", "极端派的时代.pdf"], - ["VoiceOfML/A-Historical-Learning-Data", "无产阶级政党/列宁《怎么办?》.pdf"], - ["VoiceOfML/MLMRL-Hub", "001643/学点逻辑.pdf"], - ["VoiceOfML/Omnibus", "幻の大連.pdf"], - ], - "folder": ["VoiceOfML/SovMaterials", "俄苏史/苏联史"], -} -CATALOG_CSS = """body{font:17px/1.7 system-ui,sans-serif;margin:0;background:#fafafa;color:#202124} -main{max-width:900px;margin:auto;padding:24px 18px}a{color:#1558a6}a:focus-visible{outline:3px solid #1558a6;outline-offset:3px} -h1{font-size:1.65rem;line-height:1.4;overflow-wrap:anywhere}h2{font-size:1.2rem;margin-top:1.8em} -nav,footer{margin:18px 0}li{margin:9px 0}p{margin:12px 0}dl{display:grid;grid-template-columns:5em 1fr;gap:8px} -dt{font-weight:600}dd{margin:0;overflow-wrap:anywhere}code{white-space:pre-wrap;overflow-wrap:anywhere} -.note{padding:12px;background:#edf3fa;border-radius:8px}.muted{color:#555}img{max-width:100%} -@media(prefers-color-scheme:dark){body{background:#181a1d;color:#e2e2e6}a{color:#9ec5ff}.muted{color:#bfc5cf}.note{background:#242f40}} -""" - - -def json_script(value: object) -> str: - return json.dumps(value, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029") - - -def metadata(title: str, description: str, url: str, *, canonical: bool, noindex: bool = False) -> str: - image = (PAGES if url.startswith(PAGES) else HF) + "icons/icon-512.png" - values = [f"{escape(title)}", - f''] - if canonical: - values.append(f'') - if noindex: - values.append('') - for key, value in [("og:type", "website"), ("og:site_name", "VoiceOfML"), - ("og:title", title), ("og:description", description), ("og:url", url), - ("og:image", image), ("og:image:alt", "VoiceOfML 文库"), ("og:locale", "zh_CN")]: - values.append(f'') - for key, value in [("twitter:card", "summary"), ("twitter:title", title), - ("twitter:description", description), ("twitter:image", image), - ("twitter:image:alt", "VoiceOfML 文库")]: - values.append(f'') - return "\n".join(values) - - -def enrich_search_shell(html: str, repo: str | None = None, count: int | None = None) -> str: - """HF-only: retain the platform's single HTTP canonical, never add a rival.""" - title = "VoiceOfML Search" - description = (f"检索 {repo} 的 {count:,} 条资料记录,按文件名、路径和格式查找,在线阅读或下载。" - if repo and count is not None else DESCRIPTION) - url = HF + (quote(repo.split("/")[-1], safe="") + "/" if repo else "") - start, end = "", "" - if start in html and end in html: - head = metadata(title, description, url, canonical=False) - head += '\n' - html = html.split(start, 1)[0] + start + "\n" + head + "\n" + end + html.split(end, 1)[1] - return html - - -def decode_corpus(payload: object) -> list[CatalogRecord]: - if not isinstance(payload, dict): - raise ValueError("SEO requires the current compact-v2 corpus") - payload = cast(dict[str, object], payload) - if payload.get("v") != 2: - raise ValueError("SEO requires the current compact-v2 corpus") - repos, folders, rows = payload.get("rp"), payload.get("fd"), payload.get("rc") - if not (isinstance(repos, list) and isinstance(folders, list) and isinstance(rows, list)): - raise ValueError("Invalid compact tables") - repos, folders, rows = cast(list[object], repos), cast(list[object], folders), cast(list[object], rows) - result: list[CatalogRecord] = [] - for raw_row in rows: - if not isinstance(raw_row, list): - raise ValueError("Invalid compact record reference") - row = cast(list[object], raw_row) - if (len(row) < 6 or type(row[0]) is not int - or not 0 <= row[0] < len(repos) or type(row[3]) is not int or not 0 <= row[3] < len(folders)): - raise ValueError("Invalid compact record reference") - repo, filename, extension, folder = repos[row[0]], row[1], row[2], folders[row[3]] - if (not isinstance(repo, str) or not re.fullmatch(r"VoiceOfML/[A-Za-z0-9._-]+", repo) - or not isinstance(filename, str) or not isinstance(extension, str) - or not isinstance(folder, list) - or not all(isinstance(part, str) for part in cast(list[object], folder))): - raise ValueError("Invalid compact record fields") - record: CatalogRecord = {"Repo": repo, "File": filename, "Extension": extension, - "Folder": cast(list[str], folder), "Size": row[4]} - result.append(record) - return result - - -def relative_path(record: CatalogRecord) -> str: - name = record["File"] + ("." + record["Extension"] if record["Extension"] else "") - path = "/".join([*record["Folder"], name]) - # The path is already assembled. Boundary checks avoid allocating and - # visiting a list of components for every record in the catalog. - if ("\x00" in path or "\\" in path or path in (".", "..") - or path.startswith(("./", "../")) or path.endswith(("/.", "/..")) - or "/./" in path or "/../" in path): - raise ValueError("Unsafe source path") - return path - - -def source_url(record: CatalogRecord, action: str = "resolve") -> str: - return f'https://huggingface.co/datasets/{record["Repo"]}/{action}/main/{quote(relative_path(record), safe="/")}' - - -def source_id(record: CatalogRecord) -> str: - value = 1469598103934665603 - for byte in source_url(record).encode("utf-8"): - value = ((value ^ byte) * 1099511628211) & ((1 << 64) - 1) - digits = "0123456789abcdefghijklmnopqrstuvwxyz" - result = "" - while value: - value, digit = divmod(value, 36) - result = digits[digit] + result - return result.rjust(13, "0") - - -def build_catalog(records: list[CatalogRecord], *, project: str, corpus_identity: str, pilot: Pilot | None = None) -> CatalogResult: - if project not in ("pages", "hf"): - raise ValueError("Unknown project") - pilot = PILOT if pilot is None else pilot - primary = project == "pages" - origin = PAGES if primary else HF - catalog = "catalog/" - repo_prefix = "" if primary else catalog - book_prefix = "book/" if primary else catalog + "book/" - grouped: defaultdict[str, list[CatalogRecord]] = defaultdict(list) - by_key: dict[tuple[str, str], CatalogRecord] = {} - for record in records: - grouped[record["Repo"]].append(record) - key = (record["Repo"], relative_path(record)) - if key in by_key and any(by_key[key].get(field) != record.get(field) for field in ("File", "Extension", "Folder", "Size")): - raise ValueError("Conflicting source identity") - by_key[key] = record - selected: dict[tuple[str, str], CatalogRecord] = {} - for repo, path in pilot["samples"]: - record = by_key.get((repo, path)) - if record is None: - raise ValueError(f"Missing configured SEO pilot source: {repo}/{path}") - selected[(repo, path)] = record - folder_repo, folder_path = pilot["folder"] - folder_records = [record for record in grouped[folder_repo] if "/".join(record["Folder"]) == folder_path] - descendants = [record for record in grouped[folder_repo] - if "/".join(record["Folder"]).startswith(folder_path + "/")] - if not folder_records or descendants or len(folder_records) > 64: - raise ValueError("SEO pilot must be a complete leaf folder of 1–64 files; never truncate it") - for record in folder_records: - selected[(record["Repo"], relative_path(record))] = record - selected_records = sorted(selected.values(), key=lambda record: (record["Repo"], relative_path(record))) - ids = [source_id(record) for record in selected_records] - if len(set(ids)) != len(ids): - raise ValueError("SEO source-ID collision") - folder_id = hashlib.sha256((folder_repo + "\0" + folder_path).encode()).hexdigest()[:16] - folder_route = catalog + "folders/" + folder_id + "/" - pages: dict[str, str] = {} - page_urls: list[str] = [] - - def anchor(route: str, label: str) -> str: - return f'{escape(label)}' - - def search_link(repo: str, folder: str = "") -> str: - short = quote(repo.split("/")[-1], safe="") - return origin + ("#/" + short if primary else short + "/") + ("?" + urlencode({"path": folder}) if folder else "") - - def entries(values: list[CatalogRecord]) -> str: - return "
    " + "".join("
  • " + anchor(book_prefix + source_id(record) + "/", record["File"]) - + " — " + escape(record["Extension"].upper()) + "
  • " for record in values) + "
" - - def page(route: str, title: str, description: str, body: str, entity: dict[str, object]) -> None: - url = origin + route - graph = {"@context": "https://schema.org", "@graph": [ - {"@type": "WebSite", "@id": origin + "#website", "name": "VoiceOfML", "url": origin}, - {"@type": "WebPage", "@id": url, "url": url, "name": title, "description": description, - "inLanguage": "zh-CN", "isPartOf": {"@id": origin + "#website"}, "mainEntity": entity}, - ]} - mirror = "" - # Mirror links use explicit route correspondence, not title-derived guesses. - if not primary: - main_route = route.removeprefix(catalog) if route.startswith(catalog + "book/") or route in {catalog + repo.split("/")[-1] + "/" for repo in grouped} else route - mirror = '

这是 HF 导航镜像;打开对应的主目录页。

' - html = ('' - '' - + metadata(title, description, url, canonical=primary, noindex=not primary) - + '' - + '
' - + '' - + '

' + escape(title) + '

' + mirror + body - + '
本页仅整理公开文件元数据,不代表已核实作者、出版或 OCR 准确性。' - '如资料信息或来源有误,请通过原始仓库反馈。目录试点不限制站内完整搜索。
' - + '
') - pages[route + "index.html"] = html - page_urls.append(url) - - repo_links = '
    ' + ''.join('
  • ' + anchor(repo_prefix + repo.split('/')[-1] + '/', repo.split('/')[-1]) - + f' — {len(grouped[repo]):,} 条记录
  • ' for repo in sorted(grouped)) + '
' - page(catalog, "VoiceOfML 文库目录", DESCRIPTION, - '

按来源仓库浏览公开资料。下列数量是文件元数据记录数,不是去重后的书籍数。

' + repo_links - + f'

目录试点

本批提供 {len(selected_records)} 个资源详情和一个完整叶目录;其余资料仍可通过站内搜索查找。

' - + '

' + anchor(folder_route, folder_repo.split('/')[-1] + '/' + folder_path) + '

' + entries(selected_records), - {"@type": "ItemList", "numberOfItems": len(grouped)}) - for repo in sorted(grouped): - formats = Counter(record["Extension"] for record in grouped[repo]) - top = Counter(record["Folder"][0] if record["Folder"] else "(根目录)" for record in grouped[repo]) - sample = [record for record in selected_records if record["Repo"] == repo] - body = f'

{escape(repo)} 包含 {len(grouped[repo]):,} 条文件记录,可按文件名、路径和格式检索。

' - body += '

进入此仓库的完整搜索 · 原始数据仓库

' - body += '

文件格式

' + ';'.join(escape(ext.upper() or '无扩展名') + f' {count:,}' for ext, count in sorted(formats.items())) + '

' - body += '

路径概览

以下为条目最多的至多 12 个顶层路径示例;完整目录见仓库搜索。

    ' - body += ''.join('
  • ' + escape(name) + f' — {count:,} 条
  • ' for name, count in sorted(top.items(), key=lambda item: (-item[1], item[0]))[:12]) + '
' - body += '

本批资源详情

' + entries(sample) - if repo == folder_repo: - body += '

' + anchor(folder_route, '浏览完整试点目录:' + folder_path) + '

' - page(repo_prefix + repo.split('/')[-1] + '/', repo.split('/')[-1] + ' 资料目录 — VoiceOfML', - f'{repo} 的文件目录、格式分布与来源路径;共 {len(grouped[repo]):,} 条元数据记录,支持在线检索、阅读和原始文件下载。', - body, {"@type": "CollectionPage", "name": repo}) - page(folder_route, folder_path + ' — ' + folder_repo.split('/')[-1], - f'{folder_repo}/{folder_path} 的完整叶目录,包含 {len(folder_records)} 个文件。', - '

' + anchor(repo_prefix + folder_repo.split('/')[-1] + '/', folder_repo) + '

原始目录:' - + escape(folder_path) + f';本页完整列出该叶目录的 {len(folder_records)} 个文件。

' - + entries(sorted(folder_records, key=relative_path)), {"@type": "ItemList", "numberOfItems": len(folder_records)}) - for record in selected_records: - repo, path, identifier = record['Repo'], relative_path(record), source_id(record) - size = str(record.get('Size', '未知')) + (' bytes' if type(record.get('Size')) in (int, float) else '') - body = '

' + anchor(repo_prefix + repo.split('/')[-1] + '/', repo) + '

' - for label, value in [('文件名', record['File']), ('仓库', repo), ('原始路径', path), - ('格式', record['Extension'].upper()), ('文件大小', size)]: - body += '
' + label + '
' + escape(value) + '
' - body += '

在线阅读 · ' - body += '下载原始文件 · 查看原始文件页面

' - body += '

资料说明:此条目按原始文件名和仓库路径登记;请以原文件及来源页面核对内容、版本与权利信息。本页不推测作者、ISBN 或出版日期。

' - page(book_prefix + identifier + '/', record['File'] + ' — VoiceOfML 资源详情', - f'{record["File"]},{record["Extension"].upper()} 文件,来源 {repo};查看路径、在线阅读与原始下载入口。', body, - {"@type": "DigitalDocument", "name": record['File'], "encodingFormat": record['Extension'], - "isBasedOn": source_url(record, 'blob')}) - sitemap_urls = [PAGES, *page_urls] if primary else [] - if primary: - pages['sitemap.xml'] = '' + ''.join('' + escape(url) + '' for url in sitemap_urls) + '' - manifest: dict[str, object] = {'version': 1, 'profile': 'metadata-catalog-pilot-v1', 'project': project, - 'corpus_identity': corpus_identity, 'record_count': len(records), - 'repo_counts': {repo: len(grouped[repo]) for repo in sorted(grouped)}, - 'detail_count': len(selected_records), 'folder_count': 1, 'urls': page_urls, - 'sitemap_urls': sitemap_urls, 'details': [dict(id=source_id(record), repo=record['Repo'], - path=relative_path(record), source=source_url(record)) for record in selected_records], - 'files': {path: hashlib.sha256(body.encode()).hexdigest() for path, body in sorted(pages.items())}} - return {'files': pages, 'manifest': manifest} - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--project', choices=('pages', 'hf'), required=True) - parser.add_argument('--corpus', default='data/search_data.json.gz') - parser.add_argument('--output', required=True) - args = parser.parse_args() - source = Path(args.corpus).read_bytes() - result = build_catalog(decode_corpus(json.loads(gzip.decompress(source))), project=args.project, - corpus_identity=hashlib.sha256(source).hexdigest()) - output = Path(args.output) - if (output / 'seo-publication.json').exists(): - raise ValueError('Use a fresh build output; refusing stale catalog artifacts') - if any((output / relative).exists() for relative in result['files']): - raise ValueError('Refusing to overwrite existing catalog or sitemap files') - for relative, body in result['files'].items(): - target = output / relative - target.parent.mkdir(parents=True, exist_ok=True) - target.write_text(body, encoding='utf-8') - (output / 'seo-publication.json').write_text(json.dumps(result['manifest'], ensure_ascii=False, indent=2), encoding='utf-8') - print(json.dumps({key: result['manifest'][key] for key in ('project', 'record_count', 'detail_count', 'folder_count')})) - return 0 - - -if __name__ == '__main__': - raise SystemExit(main()) +"""Compatibility import for backend.site.application.seo.""" +import sys +from backend.site.application import seo as _implementation +from backend.site.application.seo import ( + CATALOG_CSS as CATALOG_CSS, + CatalogRecord as CatalogRecord, + CatalogResult as CatalogResult, + DESCRIPTION as DESCRIPTION, + HF as HF, + PAGES as PAGES, + PILOT as PILOT, + Pilot as Pilot, + build_catalog as build_catalog, + decode_corpus as decode_corpus, + enrich_search_shell as enrich_search_shell, + json_script as json_script, + main as main, + metadata as metadata, + relative_path as relative_path, + source_id as source_id, + source_url as source_url, +) + +sys.modules[__name__] = _implementation + +if __name__ == "__main__": + raise SystemExit(_implementation.main()) diff --git a/backend/shared/__init__.py b/backend/shared/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10eabc98da935c7c196e8476b90b1239acabd317 --- /dev/null +++ b/backend/shared/__init__.py @@ -0,0 +1 @@ +"""shared package.""" diff --git a/backend/shared/cache/__init__.py b/backend/shared/cache/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..885743a6905c253567183ba710d6247d360112b9 --- /dev/null +++ b/backend/shared/cache/__init__.py @@ -0,0 +1 @@ +"""shared cache package.""" diff --git a/backend/shared/cache/core.py b/backend/shared/cache/core.py new file mode 100644 index 0000000000000000000000000000000000000000..c22dff744744021fd494a54fa6e31eab95cee137 --- /dev/null +++ b/backend/shared/cache/core.py @@ -0,0 +1,31 @@ +"""Bounded insertion-ordered response cache shared by API and search.""" +from collections.abc import Callable, Hashable +import json +import time + + +def cached(store: dict[Hashable, tuple[float, object] | tuple[float, object, int]], key: Hashable, + builder: Callable[[], object], ttl: float, limit: int, *, + max_entry_bytes: int, max_total_bytes: int) -> object: + now = time.monotonic() + cached = store.get(key) + if cached and now - cached[0] < ttl: + store[key] = store.pop(key) + return cached[1] + value = builder() + store.pop(key, None) + for old_key, entry in list(store.items()): + if now - entry[0] >= ttl: + del store[old_key] + size = (len(value) if isinstance(value, bytes) else len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))) + len(str(key).encode("utf-8")) + if size > max_entry_bytes: + return value + total = sum(entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) for entry in store.values()) + while store and (len(store) >= limit or total + size > max_total_bytes): + oldest_key = next(iter(store)) + entry = store.pop(oldest_key) + total -= entry[2] if len(entry) > 2 else len(json.dumps(entry[1]).encode("utf-8")) + if size <= max_total_bytes: + store[key] = (now, value, size) + return value + diff --git a/backend/shared/transport/__init__.py b/backend/shared/transport/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d90913c1061bac87f308a9bdd5b9f5bbab42138c --- /dev/null +++ b/backend/shared/transport/__init__.py @@ -0,0 +1 @@ +"""shared transport package.""" diff --git a/backend/shared/transport/streams.py b/backend/shared/transport/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..b27894a68f384de9f3463f8096d591cf754ed313 --- /dev/null +++ b/backend/shared/transport/streams.py @@ -0,0 +1,287 @@ +"""Own upstream responses across the route-to-ASGI streaming handoff.""" +import asyncio +import inspect +from collections.abc import AsyncIterator, Awaitable, Callable, Mapping +from types import TracebackType +import aiohttp +from fastapi.responses import StreamingResponse +from starlette.background import BackgroundTask +from starlette.responses import ContentStream, Response +from starlette.types import Receive, Scope, Send + + +class OwnedStreamingResponse(StreamingResponse): + def __init__(self, content: ContentStream, *, cleanup: Callable[[], Awaitable[None] | None], + status_code: int = 200, headers: Mapping[str, str] | None = None, + media_type: str | None = None, background: BackgroundTask | None = None) -> None: + super().__init__(content, status_code=status_code, headers=headers, media_type=media_type, background=background) + self.cleanup = cleanup + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + try: + await super().__call__(scope, receive, send) + finally: + # A disconnect may happen before the generator's first iteration. + try: + result = self.cleanup() + if inspect.isawaitable(result): + await result + finally: + close = getattr(self.body_iterator, "aclose", None) + if close is not None: + await close() + + +class UpstreamLease: + """Own an upstream response and an optional, already-acquired pool slot.""" + + def __init__(self, semaphore: asyncio.Semaphore | None = None) -> None: + self.response: aiohttp.ClientResponse | None = None + self.semaphore = semaphore + self.closed = False + self.transferred = False + + def close(self) -> None: + if self.closed: + return + try: + if self.response is not None: + self.response.release() + self.response = None + self.closed = True + finally: + if self.semaphore is not None: + self.semaphore.release() + self.semaphore = None + + def __enter__(self) -> "UpstreamLease": + return self + + def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, + traceback: TracebackType | None) -> None: + if not self.transferred: + self.close() + + async def chunks(self, error_label: str) -> AsyncIterator[bytes]: + try: + response = self.response + if response is None: + raise RuntimeError("upstream response unavailable") + async for chunk in response.content.iter_chunked(65536): + yield chunk + except Exception as exc: + print(f"{error_label}: {exc}") + raise + finally: + self.close() + + def streaming_response(self, content: ContentStream, *, status_code: int = 200, + headers: Mapping[str, str] | None = None, media_type: str | None = None, + background: BackgroundTask | None = None) -> OwnedStreamingResponse: + response = OwnedStreamingResponse(content, cleanup=self.close, status_code=status_code, + headers=headers, media_type=media_type, background=background) + self.transferred = True + return response + + +class SharedRangeFlight: + """Stream one bounded response to independently owned subscribers.""" + + def __init__(self, create: Callable[[], Awaitable[Response]], limit: int, + finished: Callable[["SharedRangeFlight"], None]) -> None: + self.create = create + self.limit = limit + self.finished = finished + self.ready: asyncio.Future[bool] = asyncio.get_running_loop().create_future() + self.ready.add_done_callback(lambda future: None if future.cancelled() else future.exception()) + self.changed = asyncio.Event() + self.started = asyncio.Event() + self.task: asyncio.Task[None] | None = None + self.response: Response | None = None + self.headers: dict[str, str] = {} + self.chunks: list[bytes | memoryview] = [] + self.size = 0 + self.subscribers = 0 + self.shared = False + self.done = False + self.error: BaseException | None = None + self.close_error: BaseException | None = None + self._response_cleaned = False + self._iterator_closed = False + + def subscribe(self) -> "RangeSubscription": + self.subscribers += 1 + if self.task is None: + self.task = asyncio.create_task(self._run()) + self.task.add_done_callback(self._settled) + return RangeSubscription(self) + + def _settled(self, task: asyncio.Task[None]) -> None: + error = asyncio.CancelledError() if task.cancelled() else task.exception() + if error is not None and self.error is None: + self.error = error + if not self.done: + self.done = True + if not self.ready.done(): + self.ready.set_exception(self.error or RuntimeError("range flight stopped")) + self.changed.set() + if not self.subscribers: + self.finished(self) + + async def _release_response(self) -> None: + response = self.response + if response is None: + return + errors: list[BaseException] = [] + cleanup = getattr(response, "cleanup", None) + try: + if not self._response_cleaned: + if cleanup: + result = cleanup() + if inspect.isawaitable(result): + await result + self._response_cleaned = True + except BaseException as exc: + errors.append(exc) + iterator = getattr(response, "body_iterator", None) + try: + if not self._iterator_closed: + if iterator is not None: + await iterator.aclose() + self._iterator_closed = True + except BaseException as exc: + errors.append(exc) + self.close_error = (errors[0] if len(errors) == 1 else + BaseExceptionGroup("Reader range response close failures", errors) if errors else None) + if self.close_error is not None: + raise self.close_error + self.response = None + + async def _run(self) -> None: + try: + self.response = await self.create() + try: + length = int(self.response.headers.get("content-length", "")) + except (TypeError, ValueError): + length = -1 + if self.response.status_code != 206 or not 0 <= length <= self.limit: + self.ready.set_result(False) + return + self.shared = True + self.headers = dict(self.response.headers) + self.ready.set_result(True) + # A transport may suppress cancellation and still return headers. + # If all waiters left, no one can start this producer; release it. + if not self.subscribers: + return + await self.started.wait() + iterator = getattr(self.response, "body_iterator", None) + if iterator is None: + body = self.response.body + if len(body) > length: + raise ValueError("shared range body exceeds declared length") + self.chunks.append(body) + self.size = len(body) + self.changed.set() + else: + async for chunk in iterator: + if self.size + len(chunk) > length: + raise ValueError("shared range body exceeds declared length") + self.chunks.append(chunk) + self.size += len(chunk) + self.changed.set() + if self.size < length: + raise ValueError("shared range body shorter than declared length") + except BaseException as error: + self.error = error + if not self.ready.done(): + self.ready.set_exception(error) + finally: + try: + if self.shared or self.error or not self.subscribers: + await self._release_response() + finally: + self.done = True + self.changed.set() + if not self.subscribers: + self.finished(self) + + def take_response(self) -> Response | None: + response, self.response = self.response, None + return response + + def unsubscribe(self) -> None: + self.subscribers -= 1 + if self.subscribers: + return + if not self.done: + if self.task is not None: + self.task.cancel() + self.finished(self) + elif self.response is not None: + # An unclaimed declined response still owns its upstream lease. + self.task = asyncio.create_task(self._close_declined()) + self.task.add_done_callback(self._settled) + else: + self.finished(self) + + async def _close_declined(self) -> None: + try: + await self._release_response() + finally: + self.finished(self) + + async def close(self) -> None: + previous_error = self.close_error + if self.task and not self.task.done(): + self.task.cancel() + if self.task: + await asyncio.gather(self.task, return_exceptions=True) + if self.close_error is not None and self.close_error is not previous_error: + raise self.close_error + await self._release_response() + self.finished(self) + + +class RangeSubscription: + def __init__(self, flight: SharedRangeFlight) -> None: + self.flight: SharedRangeFlight | None = flight + self.closed = False + + def close(self) -> None: + if not self.closed: + self.closed = True + if self.flight is not None: + self.flight.unsubscribe() + + async def release(self) -> None: + flight = self.flight + if flight is None: + return + self.close() + if not flight.subscribers and flight.task: + await asyncio.gather(flight.task, return_exceptions=True) + self.flight = None + + async def stream(self) -> AsyncIterator[bytes | memoryview]: + cursor = 0 + flight = self.flight + if flight is None: + return + flight.started.set() + try: + while not self.closed: + while cursor < len(flight.chunks): + chunk = flight.chunks[cursor] + cursor += 1 + yield chunk + if flight.done: + if flight.error: + raise flight.error + return + flight.changed.clear() + if cursor < len(flight.chunks) or flight.done: + continue + await flight.changed.wait() + finally: + await self.release() diff --git a/backend/shared/transport/upstream.py b/backend/shared/transport/upstream.py new file mode 100644 index 0000000000000000000000000000000000000000..c8dd28f6d1a0e530761a1886cb4940abb7cb6944 --- /dev/null +++ b/backend/shared/transport/upstream.py @@ -0,0 +1,329 @@ +"""Validated upstream requests and bounded redirect reuse, independent of API state.""" +import asyncio +from collections.abc import Awaitable, Callable +import re +import time +from typing import NotRequired, Protocol, TypedDict, Unpack, cast +from urllib.parse import unquote, urljoin, urlparse + +import aiohttp + +ALLOWED_DOWNLOAD_HOSTS = {"huggingface.co", "hf-mirror.com", "hf.co"} +ALLOWED_DOWNLOAD_HOST_SUFFIXES = (".hf.co", ".huggingface.co", ".xethub.hf.co") +# Redirects are a narrower trust boundary than user-supplied source URLs. Keep +# this exact-host list in sync with the signed storage targets we actually use; +# accepting every future *.hf.co host would let a redirect escape the dataset +# scope checked on the initial URL. +TRUSTED_REDIRECT_HOSTS = frozenset({ + "cdn-lfs.hf.co", "cdn-lfs.huggingface.co", "cdn-lfs-us-1.hf.co", + "cdn-lfs-us-1.huggingface.co", "us.aws.cdn.hf.co", + "cas-bridge.xethub.hf.co", "cas-server.xethub.hf.co", "transfer.xethub.hf.co", +}) +MAX_REDIRECTS = 5 +READER_ASSET_PATH_RE = re.compile( + r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|ocr-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl)|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|(?:[a-z0-9-]+/)?(?:linearized\.pdf|chapter-manifest\.json|document\.(?:pdf|epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)|book\.epub|audio\.(?:mp3|wav|m4a|flac|mpga)|video\.(?:mp4|mov)|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz)))" +) +# Converted Reader assets are served from buckets; the former +# vomebook/Reader-Assets dataset is deleted and is not a Reader source. +VOICEOFML_READER_SOURCE_RE = re.compile(r"^/datasets/VoiceOfML/[A-Za-z0-9._-]+/(?:resolve|raw)/main/.+$") +VOICEOFML_PINNED_DOCUMENT_RE = re.compile( + r"^/datasets/VoiceOfML/[A-Za-z0-9._-]+/resolve/[0-9a-f]{40}/.+\.(?i:pdf|djvu)$") +UPSTREAM_REDIRECT_TTL_SECONDS = 300 +UPSTREAM_REDIRECT_MAX_ENTRIES = 2000 +# Statuses from a cached signed target that mean it expired or moved; the +# cached entry is evicted and the redirect chain is walked once from scratch. +STALE_REDIRECT_TARGET_STATUSES = frozenset({401, 403, 404, 410}) +upstream_redirect_cache: dict[tuple[str, str], tuple[float, str]] = {} + + +def is_allowed_download_host(hostname: str | None) -> bool: + return bool(hostname) and ( + hostname in ALLOWED_DOWNLOAD_HOSTS or hostname.endswith(ALLOWED_DOWNLOAD_HOST_SUFFIXES) + ) + + +def validate_download_url(url: str) -> str: + parsed = urlparse(url) + if ( + parsed.scheme != "https" + or not is_allowed_download_host(parsed.hostname) + or parsed.port not in (None, 443) + or parsed.username is not None + or parsed.password is not None + ): + raise ValueError(f"不允许的下载跳转地址: {parsed.hostname or 'unknown'}") + return url + + +def normalize_download_url(url: str) -> str: + parsed = urlparse(url) + if parsed.hostname == "hf-mirror.com": + return parsed._replace(netloc="huggingface.co").geturl() + return url + + +def decode_url_path(path: str) -> str: + decoded_path = path + for _ in range(8): + next_path = unquote(decoded_path) + if next_path == decoded_path: + return decoded_path + decoded_path = next_path + raise ValueError("不允许的下载来源路径") + + +def validate_path_safety(path: str) -> str: + decoded_path = decode_url_path(path) + if ( + "\\" in decoded_path + or "\x00" in decoded_path + or any(part in (".", "..") for part in decoded_path.split("/")) + ): + raise ValueError("不允许的下载来源路径") + return decoded_path + + +def validate_voiceofml_source_url(url: str) -> str: + url = normalize_download_url(url) + validate_download_url(url) + parsed = urlparse(url) + decoded_path = validate_path_safety(parsed.path) + if ( + parsed.hostname != "huggingface.co" + or parsed.fragment + or parsed.query + or not decoded_path.startswith("/datasets/VoiceOfML/") + ): + raise ValueError("只允许 VoiceOfML 数据集文件") + return url + + +def validate_reader_source_url(url: str) -> str: + url = normalize_download_url(url) + validate_download_url(url) + parsed = urlparse(url) + if parsed.hostname != "huggingface.co" or parsed.fragment or parsed.query: + raise ValueError("不允许的阅读来源") + decoded_path = validate_path_safety(parsed.path) + if VOICEOFML_READER_SOURCE_RE.fullmatch(decoded_path): + return url + if (VOICEOFML_PINNED_DOCUMENT_RE.fullmatch(decoded_path) + and not any(ord(char) < 32 or ord(char) == 127 for char in decoded_path) + and not any(char in decoded_path for char in ('%', '?', '#')) and '//' not in decoded_path): + return url + raise ValueError("不允许的阅读来源") + + +def validate_voiceofml_redirect_url(url: str) -> str: + normalized = normalize_download_url(url) + validate_download_url(normalized) + if urlparse(normalized).hostname == "huggingface.co": + parsed = urlparse(normalized) + cache_source = reader_cache_source_path(parsed.path) + if cache_source is not None and not parsed.fragment: + # Hugging Face redirects existing files to commit-pinned cache + # paths. Validate the mapped dataset source while preserving the + # redirect URL and its cache metadata for the upstream request. + validate_voiceofml_source_url("https://huggingface.co" + cache_source) + return normalized + return validate_voiceofml_source_url(normalized) + if urlparse(normalized).hostname not in TRUSTED_REDIRECT_HOSTS: + raise ValueError("上游重定向超出允许的存储范围") + return normalized + + +def reader_cache_source_path(path: str) -> str | None: + """Map HF's commit-pinned cache route back to its dataset source for validation.""" + match = re.fullmatch( + r"/api/resolve-cache/datasets/([^/]+/[^/]+)/[0-9a-f]{40}/(.+)", + validate_path_safety(path), + ) + if match: + return f"/datasets/{match[1]}/resolve/main/{match[2]}" + return None + + +def validate_reader_redirect_url(url: str) -> str: + normalized = normalize_download_url(url) + validate_download_url(normalized) + if urlparse(normalized).hostname == "huggingface.co": + parsed = urlparse(normalized) + cache_source = reader_cache_source_path(parsed.path) + if cache_source is not None and not parsed.fragment: + # Only redirects may use this route and its HF query metadata. + # Apply the same dataset and path restrictions as the source. + validate_reader_source_url("https://huggingface.co" + cache_source) + return normalized + return validate_reader_source_url(normalized) + if urlparse(normalized).hostname not in TRUSTED_REDIRECT_HOSTS: + raise ValueError("上游重定向超出允许的存储范围") + return normalized + + +def validate_fixed_source_redirect_url(url: str, source_url: str) -> str: + """Accept only the exact fixed source URL or a known signed-storage target.""" + validate_download_url(url) + if url == source_url: + return url + parsed = urlparse(url) + if parsed.hostname not in TRUSTED_REDIRECT_HOSTS or parsed.fragment: + raise ValueError("上游重定向超出允许的存储范围") + return url + + +def source_url_scope(url: str) -> str | None: + parsed = urlparse(url) + if parsed.hostname != "huggingface.co": + return None + decoded_path = reader_cache_source_path(parsed.path) or validate_path_safety(parsed.path) + if decoded_path.startswith("/datasets/VoiceOfML/"): + return "voiceofml" + return None + + +def reader_redirect_matches_pinned_source(source_url: str, target_url: str) -> bool: + """A fixed revision cannot redirect to a different HF dataset file.""" + source = urlparse(source_url) + decoded = validate_path_safety(source.path) + match = re.fullmatch(r'/datasets/(VoiceOfML/[A-Za-z0-9._-]+)/resolve/([0-9a-f]{40})/(.+)', decoded) + if not match or not VOICEOFML_PINNED_DOCUMENT_RE.fullmatch(decoded): + return True + target = urlparse(target_url) + if target.hostname != 'huggingface.co': + return True # the independent redirect validator admits only signed hosts + path = validate_path_safety(target.path) + if path == decoded and not target.query and not target.fragment: + return True + cache = re.fullmatch(r'/api/resolve-cache/datasets/([^/]+/[^/]+)/([0-9a-f]{40})/(.+)', path) + return bool(cache and cache.groups() == match.groups() and not target.fragment) + + +def _redirect_cache_get(method: str, validated_url: str, url_validator: Callable[[str], str], + initial_scope: str | None) -> str | None: + entry = upstream_redirect_cache.get((method, validated_url)) + if not entry: + return None + cached_at, target = entry + if time.monotonic() - cached_at >= UPSTREAM_REDIRECT_TTL_SECONDS: + upstream_redirect_cache.pop((method, validated_url), None) + return None + try: + checked = url_validator(target) + except ValueError: + upstream_redirect_cache.pop((method, validated_url), None) + return None + if not reader_redirect_matches_pinned_source(validated_url, checked): + upstream_redirect_cache.pop((method, validated_url), None) + return None + next_scope = source_url_scope(checked) + if initial_scope is not None and next_scope is not None and next_scope != initial_scope: + upstream_redirect_cache.pop((method, validated_url), None) + return None + return checked + + +def _redirect_cache_put(method: str, validated_url: str, target: str) -> None: + upstream_redirect_cache[(method, validated_url)] = (time.monotonic(), target) + while len(upstream_redirect_cache) > UPSTREAM_REDIRECT_MAX_ENTRIES: + oldest = min(upstream_redirect_cache, key=lambda key: upstream_redirect_cache[key][0]) + upstream_redirect_cache.pop(oldest, None) + + +class RequestOptions(TypedDict): + allow_redirects: bool + timeout: aiohttp.ClientTimeout + headers: dict[str, str] + auto_decompress: NotRequired[bool] + + +class GenericRequest(Protocol): + def __call__(self, method: str, url: str, **options: Unpack[RequestOptions]) -> Awaitable[aiohttp.ClientResponse]: ... + + +class MethodRequest(Protocol): + def __call__(self, url: str, **options: Unpack[RequestOptions]) -> Awaitable[aiohttp.ClientResponse]: ... + + +async def _request(session: object, method: str, url: str, **options: Unpack[RequestOptions]) -> aiohttp.ClientResponse: + # aiohttp and test transports can expose either the generic request method + # or method-specific callables, all yielding an owned response. + request = cast(GenericRequest | None, getattr(session, "request", None)) + if request is not None: + return await request(method, url, **options) + method_request = cast(MethodRequest | None, getattr(session, method.lower(), None)) + if method_request is None: + raise ValueError(f"上游会话不支持 {method} 请求") + return await method_request(url, **options) + + +async def open_download_response( + session: object, + url: str, + timeout: aiohttp.ClientTimeout, + *, + method: str = "GET", + request_headers: dict[str, str] | None = None, + url_validator: Callable[[str], str] = validate_download_url, + redirect_validator: Callable[[str], str] | None = None, + auto_decompress: bool | None = None, + cache_redirects: bool = True, +) -> aiohttp.ClientResponse: + method = method.upper() + if method not in ("GET", "HEAD"): + raise ValueError("不支持的上游请求方法") + validated_url = url_validator(url) + redirect_validator = redirect_validator or url_validator + initial_scope = source_url_scope(validated_url) + headers = {"Accept-Encoding": "identity"} + headers.update(request_headers or {}) + request_options: RequestOptions = {"allow_redirects": False, "timeout": timeout, "headers": headers} + if auto_decompress is not None: + request_options["auto_decompress"] = auto_decompress + for attempt in range(2): + current_url = validated_url + cached = None + if attempt == 0 and cache_redirects: + cached = _redirect_cache_get(method, validated_url, redirect_validator, initial_scope) + if cached is not None: + current_url = cached + walked = current_url != validated_url + # Only a walk that started from a cached signed target may be retried; + # a fresh walk's failure is returned or raised as-is. + from_cache = cached is not None + for _ in range(MAX_REDIRECTS + 1): + try: + response = await _request( + session, method, current_url, **request_options, + ) + except (aiohttp.ClientError, asyncio.TimeoutError): + if not from_cache: + raise + upstream_redirect_cache.pop((method, validated_url), None) + break + if response.status not in (301, 302, 303, 307, 308): + if response.status in STALE_REDIRECT_TARGET_STATUSES and from_cache: + upstream_redirect_cache.pop((method, validated_url), None) + response.release() + break + # Reusing a signed target must not renew its fixed lifetime. + if (cache_redirects and walked and current_url != cached + and response.status in (200, 206, 304)): + _redirect_cache_put(method, validated_url, current_url) + return response + location = response.headers.get("Location") + response.release() + if not location: + raise ValueError("上游重定向缺少地址") + next_url = redirect_validator(urljoin(current_url, location)) + if not reader_redirect_matches_pinned_source(validated_url, next_url): + raise ValueError("固定版本文件的重定向身份不匹配") + next_scope = source_url_scope(next_url) + if initial_scope is not None and next_scope is not None and next_scope != initial_scope: + raise ValueError("上游重定向超出允许的数据集范围") + current_url = next_url + walked = True + else: + raise ValueError("上游重定向次数过多") + # Both retries must either return or raise; never leak an implicit None to + # callers that own/release the upstream response. + raise RuntimeError("上游重定向重试失败") diff --git a/backend/site/application/bootstrap.py b/backend/site/application/bootstrap.py index 70f2b5bdefb7a0e8eeb832786945e08331ed972c..73f1ee5f278f412fcfe02b5e1ea3c90f2b0f2235 100644 --- a/backend/site/application/bootstrap.py +++ b/backend/site/application/bootstrap.py @@ -6,7 +6,7 @@ from pathlib import Path import re from backend.catalog.application.metadata import RepoSummary -from backend.seo import CatalogResult +from backend.site.application.seo import CatalogResult JsonObject = dict[str, object] diff --git a/backend/site/application/seo.py b/backend/site/application/seo.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbad78afdb14a1bbd8f6fb4beb7b19d67e2aba6 --- /dev/null +++ b/backend/site/application/seo.py @@ -0,0 +1,317 @@ +"""Small, deterministic metadata catalog; no source-body downloads or search changes. + +The same file is copied to Pages' scripts/build/seo.py. Pages owns the indexable +catalog; new HF catalog pages are noindex mirrors because HF appends a Hub canonical. +""" +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import gzip +import hashlib +from html import escape +import json +from pathlib import Path +import re +from typing import TypedDict, cast +from urllib.parse import quote, urlencode + + +class CatalogRecord(TypedDict): + Repo: str + File: str + Extension: str + Folder: list[str] + Size: object + + +class Pilot(TypedDict): + samples: list[list[str]] + folder: list[str] + + +class CatalogResult(TypedDict): + files: dict[str, str] + manifest: dict[str, object] + + +PAGES = "https://vomebook.github.io/search/" +HF = "https://voiceofml-search.hf.space/" +DESCRIPTION = "检索 VoiceOfML 公开资料的文件名、路径和格式,浏览文库目录,在线阅读或下载原始文件。" +PILOT: Pilot = { + "samples": [ + ["VoiceOfML/VOMEBOOK", "马列之声ebook小组第二批成果集成赞助部分/jiang/中国社会主义时代的教育革命 研究资料集成pdf(近800种)/工农兵大学生/工农兵学员的优秀代表----曹谊林.txt"], + ["VoiceOfML/SovMaterials", "重要中文文献/斯大林著作各种/斯大林语录.txt"], + ["VoiceOfML/GPCREducation", "化学/简明化学手册.pdf"], + ["VoiceOfML/Teachers", "其他/李达/李达传记.pdf"], + ["VoiceOfML/MLMRL-Library", "历史/中国近代史1.pdf"], + ["VoiceOfML/Japanese-Materials", "极端派的时代.pdf"], + ["VoiceOfML/A-Historical-Learning-Data", "无产阶级政党/列宁《怎么办?》.pdf"], + ["VoiceOfML/MLMRL-Hub", "001643/学点逻辑.pdf"], + ["VoiceOfML/Omnibus", "幻の大連.pdf"], + ], + "folder": ["VoiceOfML/SovMaterials", "俄苏史/苏联史"], +} +CATALOG_CSS = """body{font:17px/1.7 system-ui,sans-serif;margin:0;background:#fafafa;color:#202124} +main{max-width:900px;margin:auto;padding:24px 18px}a{color:#1558a6}a:focus-visible{outline:3px solid #1558a6;outline-offset:3px} +h1{font-size:1.65rem;line-height:1.4;overflow-wrap:anywhere}h2{font-size:1.2rem;margin-top:1.8em} +nav,footer{margin:18px 0}li{margin:9px 0}p{margin:12px 0}dl{display:grid;grid-template-columns:5em 1fr;gap:8px} +dt{font-weight:600}dd{margin:0;overflow-wrap:anywhere}code{white-space:pre-wrap;overflow-wrap:anywhere} +.note{padding:12px;background:#edf3fa;border-radius:8px}.muted{color:#555}img{max-width:100%} +@media(prefers-color-scheme:dark){body{background:#181a1d;color:#e2e2e6}a{color:#9ec5ff}.muted{color:#bfc5cf}.note{background:#242f40}} +""" + + +def json_script(value: object) -> str: + return json.dumps(value, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029") + + +def metadata(title: str, description: str, url: str, *, canonical: bool, noindex: bool = False) -> str: + image = (PAGES if url.startswith(PAGES) else HF) + "icons/icon-512.png" + values = [f"{escape(title)}", + f''] + if canonical: + values.append(f'') + if noindex: + values.append('') + for key, value in [("og:type", "website"), ("og:site_name", "VoiceOfML"), + ("og:title", title), ("og:description", description), ("og:url", url), + ("og:image", image), ("og:image:alt", "VoiceOfML 文库"), ("og:locale", "zh_CN")]: + values.append(f'') + for key, value in [("twitter:card", "summary"), ("twitter:title", title), + ("twitter:description", description), ("twitter:image", image), + ("twitter:image:alt", "VoiceOfML 文库")]: + values.append(f'') + return "\n".join(values) + + +def enrich_search_shell(html: str, repo: str | None = None, count: int | None = None) -> str: + """HF-only: retain the platform's single HTTP canonical, never add a rival.""" + title = "VoiceOfML Search" + description = (f"检索 {repo} 的 {count:,} 条资料记录,按文件名、路径和格式查找,在线阅读或下载。" + if repo and count is not None else DESCRIPTION) + url = HF + (quote(repo.split("/")[-1], safe="") + "/" if repo else "") + start, end = "", "" + if start in html and end in html: + head = metadata(title, description, url, canonical=False) + head += '\n' + html = html.split(start, 1)[0] + start + "\n" + head + "\n" + end + html.split(end, 1)[1] + return html + + +def decode_corpus(payload: object) -> list[CatalogRecord]: + if not isinstance(payload, dict): + raise ValueError("SEO requires the current compact-v2 corpus") + payload = cast(dict[str, object], payload) + if payload.get("v") != 2: + raise ValueError("SEO requires the current compact-v2 corpus") + repos, folders, rows = payload.get("rp"), payload.get("fd"), payload.get("rc") + if not (isinstance(repos, list) and isinstance(folders, list) and isinstance(rows, list)): + raise ValueError("Invalid compact tables") + repos, folders, rows = cast(list[object], repos), cast(list[object], folders), cast(list[object], rows) + result: list[CatalogRecord] = [] + for raw_row in rows: + if not isinstance(raw_row, list): + raise ValueError("Invalid compact record reference") + row = cast(list[object], raw_row) + if (len(row) < 6 or type(row[0]) is not int + or not 0 <= row[0] < len(repos) or type(row[3]) is not int or not 0 <= row[3] < len(folders)): + raise ValueError("Invalid compact record reference") + repo, filename, extension, folder = repos[row[0]], row[1], row[2], folders[row[3]] + if (not isinstance(repo, str) or not re.fullmatch(r"VoiceOfML/[A-Za-z0-9._-]+", repo) + or not isinstance(filename, str) or not isinstance(extension, str) + or not isinstance(folder, list) + or not all(isinstance(part, str) for part in cast(list[object], folder))): + raise ValueError("Invalid compact record fields") + record: CatalogRecord = {"Repo": repo, "File": filename, "Extension": extension, + "Folder": cast(list[str], folder), "Size": row[4]} + result.append(record) + return result + + +def relative_path(record: CatalogRecord) -> str: + name = record["File"] + ("." + record["Extension"] if record["Extension"] else "") + path = "/".join([*record["Folder"], name]) + # The path is already assembled. Boundary checks avoid allocating and + # visiting a list of components for every record in the catalog. + if ("\x00" in path or "\\" in path or path in (".", "..") + or path.startswith(("./", "../")) or path.endswith(("/.", "/..")) + or "/./" in path or "/../" in path): + raise ValueError("Unsafe source path") + return path + + +def source_url(record: CatalogRecord, action: str = "resolve") -> str: + return f'https://huggingface.co/datasets/{record["Repo"]}/{action}/main/{quote(relative_path(record), safe="/")}' + + +def source_id(record: CatalogRecord) -> str: + value = 1469598103934665603 + for byte in source_url(record).encode("utf-8"): + value = ((value ^ byte) * 1099511628211) & ((1 << 64) - 1) + digits = "0123456789abcdefghijklmnopqrstuvwxyz" + result = "" + while value: + value, digit = divmod(value, 36) + result = digits[digit] + result + return result.rjust(13, "0") + + +def build_catalog(records: list[CatalogRecord], *, project: str, corpus_identity: str, pilot: Pilot | None = None) -> CatalogResult: + if project not in ("pages", "hf"): + raise ValueError("Unknown project") + pilot = PILOT if pilot is None else pilot + primary = project == "pages" + origin = PAGES if primary else HF + catalog = "catalog/" + repo_prefix = "" if primary else catalog + book_prefix = "book/" if primary else catalog + "book/" + grouped: defaultdict[str, list[CatalogRecord]] = defaultdict(list) + by_key: dict[tuple[str, str], CatalogRecord] = {} + for record in records: + grouped[record["Repo"]].append(record) + key = (record["Repo"], relative_path(record)) + if key in by_key and any(by_key[key].get(field) != record.get(field) for field in ("File", "Extension", "Folder", "Size")): + raise ValueError("Conflicting source identity") + by_key[key] = record + selected: dict[tuple[str, str], CatalogRecord] = {} + for repo, path in pilot["samples"]: + record = by_key.get((repo, path)) + if record is None: + raise ValueError(f"Missing configured SEO pilot source: {repo}/{path}") + selected[(repo, path)] = record + folder_repo, folder_path = pilot["folder"] + folder_records = [record for record in grouped[folder_repo] if "/".join(record["Folder"]) == folder_path] + descendants = [record for record in grouped[folder_repo] + if "/".join(record["Folder"]).startswith(folder_path + "/")] + if not folder_records or descendants or len(folder_records) > 64: + raise ValueError("SEO pilot must be a complete leaf folder of 1–64 files; never truncate it") + for record in folder_records: + selected[(record["Repo"], relative_path(record))] = record + selected_records = sorted(selected.values(), key=lambda record: (record["Repo"], relative_path(record))) + ids = [source_id(record) for record in selected_records] + if len(set(ids)) != len(ids): + raise ValueError("SEO source-ID collision") + folder_id = hashlib.sha256((folder_repo + "\0" + folder_path).encode()).hexdigest()[:16] + folder_route = catalog + "folders/" + folder_id + "/" + pages: dict[str, str] = {} + page_urls: list[str] = [] + + def anchor(route: str, label: str) -> str: + return f'{escape(label)}' + + def search_link(repo: str, folder: str = "") -> str: + short = quote(repo.split("/")[-1], safe="") + return origin + ("#/" + short if primary else short + "/") + ("?" + urlencode({"path": folder}) if folder else "") + + def entries(values: list[CatalogRecord]) -> str: + return "
    " + "".join("
  • " + anchor(book_prefix + source_id(record) + "/", record["File"]) + + " — " + escape(record["Extension"].upper()) + "
  • " for record in values) + "
" + + def page(route: str, title: str, description: str, body: str, entity: dict[str, object]) -> None: + url = origin + route + graph = {"@context": "https://schema.org", "@graph": [ + {"@type": "WebSite", "@id": origin + "#website", "name": "VoiceOfML", "url": origin}, + {"@type": "WebPage", "@id": url, "url": url, "name": title, "description": description, + "inLanguage": "zh-CN", "isPartOf": {"@id": origin + "#website"}, "mainEntity": entity}, + ]} + mirror = "" + # Mirror links use explicit route correspondence, not title-derived guesses. + if not primary: + main_route = route.removeprefix(catalog) if route.startswith(catalog + "book/") or route in {catalog + repo.split("/")[-1] + "/" for repo in grouped} else route + mirror = '

这是 HF 导航镜像;打开对应的主目录页。

' + html = ('' + '' + + metadata(title, description, url, canonical=primary, noindex=not primary) + + '' + + '
' + + '' + + '

' + escape(title) + '

' + mirror + body + + '
本页仅整理公开文件元数据,不代表已核实作者、出版或 OCR 准确性。' + '如资料信息或来源有误,请通过原始仓库反馈。目录试点不限制站内完整搜索。
' + + '
') + pages[route + "index.html"] = html + page_urls.append(url) + + repo_links = '
    ' + ''.join('
  • ' + anchor(repo_prefix + repo.split('/')[-1] + '/', repo.split('/')[-1]) + + f' — {len(grouped[repo]):,} 条记录
  • ' for repo in sorted(grouped)) + '
' + page(catalog, "VoiceOfML 文库目录", DESCRIPTION, + '

按来源仓库浏览公开资料。下列数量是文件元数据记录数,不是去重后的书籍数。

' + repo_links + + f'

目录试点

本批提供 {len(selected_records)} 个资源详情和一个完整叶目录;其余资料仍可通过站内搜索查找。

' + + '

' + anchor(folder_route, folder_repo.split('/')[-1] + '/' + folder_path) + '

' + entries(selected_records), + {"@type": "ItemList", "numberOfItems": len(grouped)}) + for repo in sorted(grouped): + formats = Counter(record["Extension"] for record in grouped[repo]) + top = Counter(record["Folder"][0] if record["Folder"] else "(根目录)" for record in grouped[repo]) + sample = [record for record in selected_records if record["Repo"] == repo] + body = f'

{escape(repo)} 包含 {len(grouped[repo]):,} 条文件记录,可按文件名、路径和格式检索。

' + body += '

进入此仓库的完整搜索 · 原始数据仓库

' + body += '

文件格式

' + ';'.join(escape(ext.upper() or '无扩展名') + f' {count:,}' for ext, count in sorted(formats.items())) + '

' + body += '

路径概览

以下为条目最多的至多 12 个顶层路径示例;完整目录见仓库搜索。

    ' + body += ''.join('
  • ' + escape(name) + f' — {count:,} 条
  • ' for name, count in sorted(top.items(), key=lambda item: (-item[1], item[0]))[:12]) + '
' + body += '

本批资源详情

' + entries(sample) + if repo == folder_repo: + body += '

' + anchor(folder_route, '浏览完整试点目录:' + folder_path) + '

' + page(repo_prefix + repo.split('/')[-1] + '/', repo.split('/')[-1] + ' 资料目录 — VoiceOfML', + f'{repo} 的文件目录、格式分布与来源路径;共 {len(grouped[repo]):,} 条元数据记录,支持在线检索、阅读和原始文件下载。', + body, {"@type": "CollectionPage", "name": repo}) + page(folder_route, folder_path + ' — ' + folder_repo.split('/')[-1], + f'{folder_repo}/{folder_path} 的完整叶目录,包含 {len(folder_records)} 个文件。', + '

' + anchor(repo_prefix + folder_repo.split('/')[-1] + '/', folder_repo) + '

原始目录:' + + escape(folder_path) + f';本页完整列出该叶目录的 {len(folder_records)} 个文件。

' + + entries(sorted(folder_records, key=relative_path)), {"@type": "ItemList", "numberOfItems": len(folder_records)}) + for record in selected_records: + repo, path, identifier = record['Repo'], relative_path(record), source_id(record) + size = str(record.get('Size', '未知')) + (' bytes' if type(record.get('Size')) in (int, float) else '') + body = '

' + anchor(repo_prefix + repo.split('/')[-1] + '/', repo) + '

' + for label, value in [('文件名', record['File']), ('仓库', repo), ('原始路径', path), + ('格式', record['Extension'].upper()), ('文件大小', size)]: + body += '
' + label + '
' + escape(value) + '
' + body += '

在线阅读 · ' + body += '下载原始文件 · 查看原始文件页面

' + body += '

资料说明:此条目按原始文件名和仓库路径登记;请以原文件及来源页面核对内容、版本与权利信息。本页不推测作者、ISBN 或出版日期。

' + page(book_prefix + identifier + '/', record['File'] + ' — VoiceOfML 资源详情', + f'{record["File"]},{record["Extension"].upper()} 文件,来源 {repo};查看路径、在线阅读与原始下载入口。', body, + {"@type": "DigitalDocument", "name": record['File'], "encodingFormat": record['Extension'], + "isBasedOn": source_url(record, 'blob')}) + sitemap_urls = [PAGES, *page_urls] if primary else [] + if primary: + pages['sitemap.xml'] = '' + ''.join('' + escape(url) + '' for url in sitemap_urls) + '' + manifest: dict[str, object] = {'version': 1, 'profile': 'metadata-catalog-pilot-v1', 'project': project, + 'corpus_identity': corpus_identity, 'record_count': len(records), + 'repo_counts': {repo: len(grouped[repo]) for repo in sorted(grouped)}, + 'detail_count': len(selected_records), 'folder_count': 1, 'urls': page_urls, + 'sitemap_urls': sitemap_urls, 'details': [dict(id=source_id(record), repo=record['Repo'], + path=relative_path(record), source=source_url(record)) for record in selected_records], + 'files': {path: hashlib.sha256(body.encode()).hexdigest() for path, body in sorted(pages.items())}} + return {'files': pages, 'manifest': manifest} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--project', choices=('pages', 'hf'), required=True) + parser.add_argument('--corpus', default='data/search_data.json.gz') + parser.add_argument('--output', required=True) + args = parser.parse_args() + source = Path(args.corpus).read_bytes() + result = build_catalog(decode_corpus(json.loads(gzip.decompress(source))), project=args.project, + corpus_identity=hashlib.sha256(source).hexdigest()) + output = Path(args.output) + if (output / 'seo-publication.json').exists(): + raise ValueError('Use a fresh build output; refusing stale catalog artifacts') + if any((output / relative).exists() for relative in result['files']): + raise ValueError('Refusing to overwrite existing catalog or sitemap files') + for relative, body in result['files'].items(): + target = output / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(body, encoding='utf-8') + (output / 'seo-publication.json').write_text(json.dumps(result['manifest'], ensure_ascii=False, indent=2), encoding='utf-8') + print(json.dumps({key: result['manifest'][key] for key in ('project', 'record_count', 'detail_count', 'folder_count')})) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/backend/site/http/responses.py b/backend/site/http/responses.py index 895db54f98875eb59226810bdcd9b04c9df2c2c6..979b203a7d022e70bee71877c8e771a30ce6a7dd 100644 --- a/backend/site/http/responses.py +++ b/backend/site/http/responses.py @@ -7,7 +7,7 @@ from urllib.parse import quote from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response -from backend.seo import CatalogResult +from backend.site.application.seo import CatalogResult JsonObject = dict[str, object] diff --git a/backend/upstream_http.py b/backend/upstream_http.py index c8dd28f6d1a0e530761a1886cb4940abb7cb6944..4832f1396cc89f2f7856f3860d9534fdbcb0d649 100644 --- a/backend/upstream_http.py +++ b/backend/upstream_http.py @@ -1,329 +1,35 @@ -"""Validated upstream requests and bounded redirect reuse, independent of API state.""" -import asyncio -from collections.abc import Awaitable, Callable -import re -import time -from typing import NotRequired, Protocol, TypedDict, Unpack, cast -from urllib.parse import unquote, urljoin, urlparse - -import aiohttp - -ALLOWED_DOWNLOAD_HOSTS = {"huggingface.co", "hf-mirror.com", "hf.co"} -ALLOWED_DOWNLOAD_HOST_SUFFIXES = (".hf.co", ".huggingface.co", ".xethub.hf.co") -# Redirects are a narrower trust boundary than user-supplied source URLs. Keep -# this exact-host list in sync with the signed storage targets we actually use; -# accepting every future *.hf.co host would let a redirect escape the dataset -# scope checked on the initial URL. -TRUSTED_REDIRECT_HOSTS = frozenset({ - "cdn-lfs.hf.co", "cdn-lfs.huggingface.co", "cdn-lfs-us-1.hf.co", - "cdn-lfs-us-1.huggingface.co", "us.aws.cdn.hf.co", - "cas-bridge.xethub.hf.co", "cas-server.xethub.hf.co", "transfer.xethub.hf.co", -}) -MAX_REDIRECTS = 5 -READER_ASSET_PATH_RE = re.compile( - r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|ocr-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl)|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|(?:[a-z0-9-]+/)?(?:linearized\.pdf|chapter-manifest\.json|document\.(?:pdf|epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)|book\.epub|audio\.(?:mp3|wav|m4a|flac|mpga)|video\.(?:mp4|mov)|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz)))" +"""Compatibility import for backend.shared.transport.upstream.""" +import sys +from backend.shared.transport import upstream as _implementation +from backend.shared.transport.upstream import ( + ALLOWED_DOWNLOAD_HOSTS as ALLOWED_DOWNLOAD_HOSTS, + ALLOWED_DOWNLOAD_HOST_SUFFIXES as ALLOWED_DOWNLOAD_HOST_SUFFIXES, + GenericRequest as GenericRequest, + MAX_REDIRECTS as MAX_REDIRECTS, + MethodRequest as MethodRequest, + READER_ASSET_PATH_RE as READER_ASSET_PATH_RE, + RequestOptions as RequestOptions, + STALE_REDIRECT_TARGET_STATUSES as STALE_REDIRECT_TARGET_STATUSES, + TRUSTED_REDIRECT_HOSTS as TRUSTED_REDIRECT_HOSTS, + UPSTREAM_REDIRECT_MAX_ENTRIES as UPSTREAM_REDIRECT_MAX_ENTRIES, + UPSTREAM_REDIRECT_TTL_SECONDS as UPSTREAM_REDIRECT_TTL_SECONDS, + VOICEOFML_PINNED_DOCUMENT_RE as VOICEOFML_PINNED_DOCUMENT_RE, + VOICEOFML_READER_SOURCE_RE as VOICEOFML_READER_SOURCE_RE, + decode_url_path as decode_url_path, + is_allowed_download_host as is_allowed_download_host, + normalize_download_url as normalize_download_url, + open_download_response as open_download_response, + reader_cache_source_path as reader_cache_source_path, + reader_redirect_matches_pinned_source as reader_redirect_matches_pinned_source, + source_url_scope as source_url_scope, + upstream_redirect_cache as upstream_redirect_cache, + validate_download_url as validate_download_url, + validate_fixed_source_redirect_url as validate_fixed_source_redirect_url, + validate_path_safety as validate_path_safety, + validate_reader_redirect_url as validate_reader_redirect_url, + validate_reader_source_url as validate_reader_source_url, + validate_voiceofml_redirect_url as validate_voiceofml_redirect_url, + validate_voiceofml_source_url as validate_voiceofml_source_url, ) -# Converted Reader assets are served from buckets; the former -# vomebook/Reader-Assets dataset is deleted and is not a Reader source. -VOICEOFML_READER_SOURCE_RE = re.compile(r"^/datasets/VoiceOfML/[A-Za-z0-9._-]+/(?:resolve|raw)/main/.+$") -VOICEOFML_PINNED_DOCUMENT_RE = re.compile( - r"^/datasets/VoiceOfML/[A-Za-z0-9._-]+/resolve/[0-9a-f]{40}/.+\.(?i:pdf|djvu)$") -UPSTREAM_REDIRECT_TTL_SECONDS = 300 -UPSTREAM_REDIRECT_MAX_ENTRIES = 2000 -# Statuses from a cached signed target that mean it expired or moved; the -# cached entry is evicted and the redirect chain is walked once from scratch. -STALE_REDIRECT_TARGET_STATUSES = frozenset({401, 403, 404, 410}) -upstream_redirect_cache: dict[tuple[str, str], tuple[float, str]] = {} - - -def is_allowed_download_host(hostname: str | None) -> bool: - return bool(hostname) and ( - hostname in ALLOWED_DOWNLOAD_HOSTS or hostname.endswith(ALLOWED_DOWNLOAD_HOST_SUFFIXES) - ) - - -def validate_download_url(url: str) -> str: - parsed = urlparse(url) - if ( - parsed.scheme != "https" - or not is_allowed_download_host(parsed.hostname) - or parsed.port not in (None, 443) - or parsed.username is not None - or parsed.password is not None - ): - raise ValueError(f"不允许的下载跳转地址: {parsed.hostname or 'unknown'}") - return url - - -def normalize_download_url(url: str) -> str: - parsed = urlparse(url) - if parsed.hostname == "hf-mirror.com": - return parsed._replace(netloc="huggingface.co").geturl() - return url - - -def decode_url_path(path: str) -> str: - decoded_path = path - for _ in range(8): - next_path = unquote(decoded_path) - if next_path == decoded_path: - return decoded_path - decoded_path = next_path - raise ValueError("不允许的下载来源路径") - - -def validate_path_safety(path: str) -> str: - decoded_path = decode_url_path(path) - if ( - "\\" in decoded_path - or "\x00" in decoded_path - or any(part in (".", "..") for part in decoded_path.split("/")) - ): - raise ValueError("不允许的下载来源路径") - return decoded_path - - -def validate_voiceofml_source_url(url: str) -> str: - url = normalize_download_url(url) - validate_download_url(url) - parsed = urlparse(url) - decoded_path = validate_path_safety(parsed.path) - if ( - parsed.hostname != "huggingface.co" - or parsed.fragment - or parsed.query - or not decoded_path.startswith("/datasets/VoiceOfML/") - ): - raise ValueError("只允许 VoiceOfML 数据集文件") - return url - - -def validate_reader_source_url(url: str) -> str: - url = normalize_download_url(url) - validate_download_url(url) - parsed = urlparse(url) - if parsed.hostname != "huggingface.co" or parsed.fragment or parsed.query: - raise ValueError("不允许的阅读来源") - decoded_path = validate_path_safety(parsed.path) - if VOICEOFML_READER_SOURCE_RE.fullmatch(decoded_path): - return url - if (VOICEOFML_PINNED_DOCUMENT_RE.fullmatch(decoded_path) - and not any(ord(char) < 32 or ord(char) == 127 for char in decoded_path) - and not any(char in decoded_path for char in ('%', '?', '#')) and '//' not in decoded_path): - return url - raise ValueError("不允许的阅读来源") - - -def validate_voiceofml_redirect_url(url: str) -> str: - normalized = normalize_download_url(url) - validate_download_url(normalized) - if urlparse(normalized).hostname == "huggingface.co": - parsed = urlparse(normalized) - cache_source = reader_cache_source_path(parsed.path) - if cache_source is not None and not parsed.fragment: - # Hugging Face redirects existing files to commit-pinned cache - # paths. Validate the mapped dataset source while preserving the - # redirect URL and its cache metadata for the upstream request. - validate_voiceofml_source_url("https://huggingface.co" + cache_source) - return normalized - return validate_voiceofml_source_url(normalized) - if urlparse(normalized).hostname not in TRUSTED_REDIRECT_HOSTS: - raise ValueError("上游重定向超出允许的存储范围") - return normalized - - -def reader_cache_source_path(path: str) -> str | None: - """Map HF's commit-pinned cache route back to its dataset source for validation.""" - match = re.fullmatch( - r"/api/resolve-cache/datasets/([^/]+/[^/]+)/[0-9a-f]{40}/(.+)", - validate_path_safety(path), - ) - if match: - return f"/datasets/{match[1]}/resolve/main/{match[2]}" - return None - - -def validate_reader_redirect_url(url: str) -> str: - normalized = normalize_download_url(url) - validate_download_url(normalized) - if urlparse(normalized).hostname == "huggingface.co": - parsed = urlparse(normalized) - cache_source = reader_cache_source_path(parsed.path) - if cache_source is not None and not parsed.fragment: - # Only redirects may use this route and its HF query metadata. - # Apply the same dataset and path restrictions as the source. - validate_reader_source_url("https://huggingface.co" + cache_source) - return normalized - return validate_reader_source_url(normalized) - if urlparse(normalized).hostname not in TRUSTED_REDIRECT_HOSTS: - raise ValueError("上游重定向超出允许的存储范围") - return normalized - - -def validate_fixed_source_redirect_url(url: str, source_url: str) -> str: - """Accept only the exact fixed source URL or a known signed-storage target.""" - validate_download_url(url) - if url == source_url: - return url - parsed = urlparse(url) - if parsed.hostname not in TRUSTED_REDIRECT_HOSTS or parsed.fragment: - raise ValueError("上游重定向超出允许的存储范围") - return url - - -def source_url_scope(url: str) -> str | None: - parsed = urlparse(url) - if parsed.hostname != "huggingface.co": - return None - decoded_path = reader_cache_source_path(parsed.path) or validate_path_safety(parsed.path) - if decoded_path.startswith("/datasets/VoiceOfML/"): - return "voiceofml" - return None - - -def reader_redirect_matches_pinned_source(source_url: str, target_url: str) -> bool: - """A fixed revision cannot redirect to a different HF dataset file.""" - source = urlparse(source_url) - decoded = validate_path_safety(source.path) - match = re.fullmatch(r'/datasets/(VoiceOfML/[A-Za-z0-9._-]+)/resolve/([0-9a-f]{40})/(.+)', decoded) - if not match or not VOICEOFML_PINNED_DOCUMENT_RE.fullmatch(decoded): - return True - target = urlparse(target_url) - if target.hostname != 'huggingface.co': - return True # the independent redirect validator admits only signed hosts - path = validate_path_safety(target.path) - if path == decoded and not target.query and not target.fragment: - return True - cache = re.fullmatch(r'/api/resolve-cache/datasets/([^/]+/[^/]+)/([0-9a-f]{40})/(.+)', path) - return bool(cache and cache.groups() == match.groups() and not target.fragment) - - -def _redirect_cache_get(method: str, validated_url: str, url_validator: Callable[[str], str], - initial_scope: str | None) -> str | None: - entry = upstream_redirect_cache.get((method, validated_url)) - if not entry: - return None - cached_at, target = entry - if time.monotonic() - cached_at >= UPSTREAM_REDIRECT_TTL_SECONDS: - upstream_redirect_cache.pop((method, validated_url), None) - return None - try: - checked = url_validator(target) - except ValueError: - upstream_redirect_cache.pop((method, validated_url), None) - return None - if not reader_redirect_matches_pinned_source(validated_url, checked): - upstream_redirect_cache.pop((method, validated_url), None) - return None - next_scope = source_url_scope(checked) - if initial_scope is not None and next_scope is not None and next_scope != initial_scope: - upstream_redirect_cache.pop((method, validated_url), None) - return None - return checked - - -def _redirect_cache_put(method: str, validated_url: str, target: str) -> None: - upstream_redirect_cache[(method, validated_url)] = (time.monotonic(), target) - while len(upstream_redirect_cache) > UPSTREAM_REDIRECT_MAX_ENTRIES: - oldest = min(upstream_redirect_cache, key=lambda key: upstream_redirect_cache[key][0]) - upstream_redirect_cache.pop(oldest, None) - - -class RequestOptions(TypedDict): - allow_redirects: bool - timeout: aiohttp.ClientTimeout - headers: dict[str, str] - auto_decompress: NotRequired[bool] - - -class GenericRequest(Protocol): - def __call__(self, method: str, url: str, **options: Unpack[RequestOptions]) -> Awaitable[aiohttp.ClientResponse]: ... - - -class MethodRequest(Protocol): - def __call__(self, url: str, **options: Unpack[RequestOptions]) -> Awaitable[aiohttp.ClientResponse]: ... - - -async def _request(session: object, method: str, url: str, **options: Unpack[RequestOptions]) -> aiohttp.ClientResponse: - # aiohttp and test transports can expose either the generic request method - # or method-specific callables, all yielding an owned response. - request = cast(GenericRequest | None, getattr(session, "request", None)) - if request is not None: - return await request(method, url, **options) - method_request = cast(MethodRequest | None, getattr(session, method.lower(), None)) - if method_request is None: - raise ValueError(f"上游会话不支持 {method} 请求") - return await method_request(url, **options) - -async def open_download_response( - session: object, - url: str, - timeout: aiohttp.ClientTimeout, - *, - method: str = "GET", - request_headers: dict[str, str] | None = None, - url_validator: Callable[[str], str] = validate_download_url, - redirect_validator: Callable[[str], str] | None = None, - auto_decompress: bool | None = None, - cache_redirects: bool = True, -) -> aiohttp.ClientResponse: - method = method.upper() - if method not in ("GET", "HEAD"): - raise ValueError("不支持的上游请求方法") - validated_url = url_validator(url) - redirect_validator = redirect_validator or url_validator - initial_scope = source_url_scope(validated_url) - headers = {"Accept-Encoding": "identity"} - headers.update(request_headers or {}) - request_options: RequestOptions = {"allow_redirects": False, "timeout": timeout, "headers": headers} - if auto_decompress is not None: - request_options["auto_decompress"] = auto_decompress - for attempt in range(2): - current_url = validated_url - cached = None - if attempt == 0 and cache_redirects: - cached = _redirect_cache_get(method, validated_url, redirect_validator, initial_scope) - if cached is not None: - current_url = cached - walked = current_url != validated_url - # Only a walk that started from a cached signed target may be retried; - # a fresh walk's failure is returned or raised as-is. - from_cache = cached is not None - for _ in range(MAX_REDIRECTS + 1): - try: - response = await _request( - session, method, current_url, **request_options, - ) - except (aiohttp.ClientError, asyncio.TimeoutError): - if not from_cache: - raise - upstream_redirect_cache.pop((method, validated_url), None) - break - if response.status not in (301, 302, 303, 307, 308): - if response.status in STALE_REDIRECT_TARGET_STATUSES and from_cache: - upstream_redirect_cache.pop((method, validated_url), None) - response.release() - break - # Reusing a signed target must not renew its fixed lifetime. - if (cache_redirects and walked and current_url != cached - and response.status in (200, 206, 304)): - _redirect_cache_put(method, validated_url, current_url) - return response - location = response.headers.get("Location") - response.release() - if not location: - raise ValueError("上游重定向缺少地址") - next_url = redirect_validator(urljoin(current_url, location)) - if not reader_redirect_matches_pinned_source(validated_url, next_url): - raise ValueError("固定版本文件的重定向身份不匹配") - next_scope = source_url_scope(next_url) - if initial_scope is not None and next_scope is not None and next_scope != initial_scope: - raise ValueError("上游重定向超出允许的数据集范围") - current_url = next_url - walked = True - else: - raise ValueError("上游重定向次数过多") - # Both retries must either return or raise; never leak an implicit None to - # callers that own/release the upstream response. - raise RuntimeError("上游重定向重试失败") +sys.modules[__name__] = _implementation diff --git a/config/types/jsconfig.check.json b/config/types/jsconfig.check.json index de2e3ace7c6d98977a9147a5494224bb08e3da35..486da95d87f756bede51025394469553a9d4412a 100644 --- a/config/types/jsconfig.check.json +++ b/config/types/jsconfig.check.json @@ -84,14 +84,14 @@ "../../static/reader/ui/reader-toc.mjs", "../../static/reader/ui/reader-ui.mjs", "../../static/reader/ui/reader-scroll-anchor.js", - "../../static/search/download-controller.js", + "../../static/search/downloads/application/controller.js", "../../typings/search-execution.d.ts", "../../static/search/execution/domain/policy.js", "../../static/search/execution/application/controller.js", "../../typings/search-downloads.d.ts", "../../static/search/downloads/application/batch.js", "../../static/search/downloads/presentation/queue.js", - "../../static/search/reader-navigation.js", + "../../static/search/reader-host/application/navigation.js", "../../typings/search-reader-host.d.ts", "../../typings/search-positions.d.ts", "../../typings/search-restoration.d.ts", @@ -129,20 +129,20 @@ "../../static/search/positions/application/restoration.js", "../../static/search/reader-host/presentation/return-position.js", "../../static/search/reader-host/application/host.js", - "../../static/search/search-session.js", - "../../static/search/size-format.js", - "../../static/search/record-path.js", - "../../static/search/highlight.js", - "../../static/search/response-cache.js", + "../../static/search/execution/application/session.js", + "../../static/search/results/presentation/size-format.js", + "../../static/search/catalog/domain/record-path.js", + "../../static/search/results/presentation/highlight.js", + "../../static/search/requests/infrastructure/response-cache.js", "../../typings/search-response-store.d.ts", "../../typings/search-catalog.d.ts", "../../static/search/catalog/domain/sidebar-payload.js", "../../static/search/catalog/application/client.js", "../../static/search/requests/application/response-store.js", - "../../static/search/file-types.js", - "../../static/search/response-validation.js", - "../../static/search/result-identity.js", - "../../static/search/folder-selection.js", + "../../static/search/catalog/domain/file-types.js", + "../../static/search/requests/domain/response-validation.js", + "../../static/search/results/domain/result-identity.js", + "../../static/search/sidebar/domain/folder-selection.js", "../../static/search/input/domain/ownership.js", "../../static/search/input/application/controller.js", "../../static/search/results/domain/paging-policy.js", diff --git a/config/types/jsconfig.search-exact.json b/config/types/jsconfig.search-exact.json index 7e83330a604f756a1b4bf7caba013d6e201b2467..a4a764bd31ad96d719231a3d8044ed848a5429bb 100644 --- a/config/types/jsconfig.search-exact.json +++ b/config/types/jsconfig.search-exact.json @@ -13,8 +13,8 @@ "files": [ "../../typings/reader-globals.d.ts", "../../typings/search-sidebar.d.ts", - "../../static/search/search-session.js", - "../../static/search/reader-navigation.js", + "../../static/search/execution/application/session.js", + "../../static/search/reader-host/application/navigation.js", "../../typings/search-reader-host.d.ts", "../../typings/search-positions.d.ts", "../../typings/search-restoration.d.ts", @@ -52,15 +52,15 @@ "../../static/search/positions/application/restoration.js", "../../static/search/reader-host/presentation/return-position.js", "../../static/search/reader-host/application/host.js", - "../../static/search/download-controller.js", + "../../static/search/downloads/application/controller.js", "../../typings/search-execution.d.ts", "../../static/search/execution/domain/policy.js", "../../static/search/execution/application/controller.js", "../../typings/search-downloads.d.ts", "../../static/search/downloads/application/batch.js", "../../static/search/downloads/presentation/queue.js", - "../../static/search/result-identity.js", - "../../static/search/folder-selection.js", + "../../static/search/results/domain/result-identity.js", + "../../static/search/sidebar/domain/folder-selection.js", "../../static/search/input/domain/ownership.js", "../../static/search/input/application/controller.js", "../../static/search/results/domain/paging-policy.js", @@ -82,16 +82,16 @@ "../../static/search/sidebar/infrastructure/scroll.js", "../../static/search/sidebar/presentation/directory.js", "../../static/search/sidebar/application/directory.js", - "../../static/search/record-path.js", - "../../static/search/response-validation.js", - "../../static/search/response-cache.js", + "../../static/search/catalog/domain/record-path.js", + "../../static/search/requests/domain/response-validation.js", + "../../static/search/requests/infrastructure/response-cache.js", "../../typings/search-response-store.d.ts", "../../typings/search-catalog.d.ts", "../../static/search/catalog/domain/sidebar-payload.js", "../../static/search/catalog/application/client.js", "../../static/search/requests/application/response-store.js", - "../../static/search/file-types.js", - "../../static/search/highlight.js", - "../../static/search/size-format.js" + "../../static/search/catalog/domain/file-types.js", + "../../static/search/results/presentation/highlight.js", + "../../static/search/results/presentation/size-format.js" ] } diff --git a/config/types/jsconfig.strict.json b/config/types/jsconfig.strict.json index 0c55e08800e9bef732390e19c666ff0153ab90e6..d859b2c71a1feb44b6ea11fb7569b3f65006c880 100644 --- a/config/types/jsconfig.strict.json +++ b/config/types/jsconfig.strict.json @@ -66,8 +66,8 @@ "../../static/reader/pdf/reader-pdf-range-cache.mjs", "../../static/reader/pdf/reader-pdf-range-hints.mjs", "../../static/reader/pdf/reader-pdf-text-store.mjs", - "../../static/search/search-session.js", - "../../static/search/reader-navigation.js", + "../../static/search/execution/application/session.js", + "../../static/search/reader-host/application/navigation.js", "../../typings/search-reader-host.d.ts", "../../typings/search-positions.d.ts", "../../typings/search-restoration.d.ts", @@ -105,26 +105,26 @@ "../../static/search/positions/application/restoration.js", "../../static/search/reader-host/presentation/return-position.js", "../../static/search/reader-host/application/host.js", - "../../static/search/download-controller.js", + "../../static/search/downloads/application/controller.js", "../../typings/search-execution.d.ts", "../../static/search/execution/domain/policy.js", "../../static/search/execution/application/controller.js", "../../typings/search-downloads.d.ts", "../../static/search/downloads/application/batch.js", "../../static/search/downloads/presentation/queue.js", - "../../static/search/size-format.js", - "../../static/search/record-path.js", - "../../static/search/highlight.js", - "../../static/search/response-cache.js", + "../../static/search/results/presentation/size-format.js", + "../../static/search/catalog/domain/record-path.js", + "../../static/search/results/presentation/highlight.js", + "../../static/search/requests/infrastructure/response-cache.js", "../../typings/search-response-store.d.ts", "../../typings/search-catalog.d.ts", "../../static/search/catalog/domain/sidebar-payload.js", "../../static/search/catalog/application/client.js", "../../static/search/requests/application/response-store.js", - "../../static/search/file-types.js", - "../../static/search/response-validation.js", - "../../static/search/result-identity.js", - "../../static/search/folder-selection.js", + "../../static/search/catalog/domain/file-types.js", + "../../static/search/requests/domain/response-validation.js", + "../../static/search/results/domain/result-identity.js", + "../../static/search/sidebar/domain/folder-selection.js", "../../static/search/input/domain/ownership.js", "../../static/search/input/application/controller.js", "../../static/search/results/domain/paging-policy.js", diff --git a/eslint.config.mjs b/eslint.config.mjs index ab71390e1ed695308d9e2f1d61a7f0d707097d4f..307d173f3911a219c237411b631095d47a947176 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -35,7 +35,7 @@ export default [ } }, { files: ["static/**/*.js"], languageOptions: { sourceType: "script" } }, - { files: ["static/search/result-identity.js"], languageOptions: { globals: { buildRecordRelativePath: "readonly" } } }, + { files: ["static/search/results/domain/result-identity.js"], languageOptions: { globals: { buildRecordRelativePath: "readonly" } } }, { files: ["static/search/catalog/application/client.js"], languageOptions: { globals: { BoundedResponseCache: "readonly", VoiceOfMLCatalogSidebarPayload: "readonly" } } }, { files: ["static/search/requests/application/response-store.js"], languageOptions: { globals: { BoundedResponseCache: "readonly" } } }, { files: ["static/app.js"], languageOptions: { globals: { diff --git a/pyrightconfig.strict.json b/pyrightconfig.strict.json index c56def22694cbe3b0f66ff2dae87330207538d8b..f6127ca5d045607f8c4c500006eb8cc22f5962f1 100644 --- a/pyrightconfig.strict.json +++ b/pyrightconfig.strict.json @@ -2,106 +2,141 @@ "include": [ "app.py", "backend/__init__.py", + "backend/app.py", + "backend/cache_core.py", "backend/catalog/__init__.py", "backend/catalog/application/__init__.py", "backend/catalog/application/metadata.py", "backend/catalog/http/__init__.py", "backend/catalog/http/responses.py", - "backend/site/__init__.py", - "backend/site/application/__init__.py", - "backend/site/application/bootstrap.py", - "backend/site/http/__init__.py", - "backend/site/http/responses.py", - "backend/runtime/__init__.py", - "backend/runtime/application/__init__.py", - "backend/runtime/application/lifecycle.py", - "backend/search_execution.py", - "backend/search/__init__.py", - "backend/search/corpus/__init__.py", - "backend/search/corpus/application/__init__.py", - "backend/search/corpus/application/preparation.py", - "backend/search/corpus/domain/__init__.py", - "backend/search/corpus/domain/metadata.py", - "backend/search/application/__init__.py", - "backend/search/application/requests.py", - "backend/search/application/execution.py", - "backend/search/application/cached.py", - "backend/search/domain/__init__.py", - "backend/search/domain/ordering.py", - "backend/search/domain/projection.py", - "backend/search/http/__init__.py", - "backend/search/http/schemas.py", - "backend/search/http/responses.py", - "backend/search_transport.py", - "backend/search_data_selector.py", - "backend/search_runtime_entry.py", - "backend/upstream_http.py", - "backend/search_indexes.py", "backend/data_formats.py", - "backend/proxy_streams.py", - "backend/download_warm.py", "backend/download/__init__.py", + "backend/download/application/__init__.py", + "backend/download/application/warming.py", "backend/download/domain/__init__.py", "backend/download/domain/filename.py", "backend/download/http/__init__.py", "backend/download/http/routes.py", - "backend/reader_range_cache.py", - "backend/reader_assets.py", - "backend/reader_v3_catalog.py", - "backend/record_metadata.py", - "backend/seo.py", - "backend/cache_core.py", - "backend/search_matching.py", - "backend/reader_identity.py", - "backend/reader_index.py", - "backend/reader_ocr.py", - "backend/search_filters.py", - "backend/search_words.py", - "backend/folder_tree.py", + "backend/download_warm.py", "backend/folder_contents.py", - "backend/search_projection.py", - "backend/search_candidates.py", - "backend/search_browse.py", - "backend/search_term_candidates.py", - "backend/search_bootstrap.py", - "backend/reader_archive.py", + "backend/folder_tree.py", + "backend/proxy_streams.py", "backend/reader/__init__.py", - "backend/reader/query/__init__.py", - "backend/reader/query/domain/__init__.py", - "backend/reader/query/domain/identity.py", - "backend/reader/query/application/__init__.py", - "backend/reader/query/application/resolution.py", - "backend/reader/query/application/ocr.py", - "backend/reader/query/http/__init__.py", - "backend/reader/query/http/routes.py", - "backend/reader/catalog/__init__.py", - "backend/reader/catalog/application/__init__.py", - "backend/reader/catalog/application/indexes.py", - "backend/reader/catalog/application/pool.py", - "backend/reader/catalog/http/__init__.py", - "backend/reader/catalog/http/random.py", "backend/reader/archive/__init__.py", "backend/reader/archive/application/__init__.py", "backend/reader/archive/application/archives.py", "backend/reader/archive/domain/__init__.py", "backend/reader/archive/domain/content.py", + "backend/reader/archive/domain/validation.py", "backend/reader/archive/http/__init__.py", "backend/reader/archive/http/routes.py", "backend/reader/bucket/__init__.py", - "backend/reader/bucket/domain/__init__.py", - "backend/reader/bucket/domain/policy.py", "backend/reader/bucket/application/__init__.py", "backend/reader/bucket/application/resources.py", + "backend/reader/bucket/domain/__init__.py", + "backend/reader/bucket/domain/policy.py", "backend/reader/bucket/http/__init__.py", "backend/reader/bucket/http/routes.py", + "backend/reader/catalog/__init__.py", + "backend/reader/catalog/application/__init__.py", + "backend/reader/catalog/application/indexes.py", + "backend/reader/catalog/application/pool.py", + "backend/reader/catalog/domain/__init__.py", + "backend/reader/catalog/domain/assets.py", + "backend/reader/catalog/domain/index.py", + "backend/reader/catalog/http/__init__.py", + "backend/reader/catalog/http/random.py", + "backend/reader/catalog/infrastructure/__init__.py", + "backend/reader/catalog/infrastructure/v3.py", "backend/reader/document/__init__.py", "backend/reader/document/application/__init__.py", "backend/reader/document/application/ranges.py", "backend/reader/document/domain/__init__.py", "backend/reader/document/domain/policy.py", + "backend/reader/document/domain/range_cache.py", "backend/reader/document/http/__init__.py", "backend/reader/document/http/transport.py", - "backend/app.py" + "backend/reader/query/__init__.py", + "backend/reader/query/application/__init__.py", + "backend/reader/query/application/ocr.py", + "backend/reader/query/application/resolution.py", + "backend/reader/query/domain/__init__.py", + "backend/reader/query/domain/identity.py", + "backend/reader/query/domain/ocr.py", + "backend/reader/query/http/__init__.py", + "backend/reader/query/http/routes.py", + "backend/reader_archive.py", + "backend/reader_assets.py", + "backend/reader_identity.py", + "backend/reader_index.py", + "backend/reader_ocr.py", + "backend/reader_range_cache.py", + "backend/reader_v3_catalog.py", + "backend/record_metadata.py", + "backend/runtime/__init__.py", + "backend/runtime/application/__init__.py", + "backend/runtime/application/lifecycle.py", + "backend/search/__init__.py", + "backend/search/application/__init__.py", + "backend/search/application/bootstrap.py", + "backend/search/application/cached.py", + "backend/search/application/execution.py", + "backend/search/application/requests.py", + "backend/search/corpus/__init__.py", + "backend/search/corpus/application/__init__.py", + "backend/search/corpus/application/preparation.py", + "backend/search/corpus/domain/__init__.py", + "backend/search/corpus/domain/folder_contents.py", + "backend/search/corpus/domain/folder_tree.py", + "backend/search/corpus/domain/formats.py", + "backend/search/corpus/domain/metadata.py", + "backend/search/corpus/domain/records.py", + "backend/search/corpus/domain/words.py", + "backend/search/corpus/infrastructure/__init__.py", + "backend/search/corpus/infrastructure/indexes.py", + "backend/search/corpus/infrastructure/selection.py", + "backend/search/domain/__init__.py", + "backend/search/domain/browse.py", + "backend/search/domain/candidates.py", + "backend/search/domain/filters.py", + "backend/search/domain/matching.py", + "backend/search/domain/ordering.py", + "backend/search/domain/projection.py", + "backend/search/domain/term_candidates.py", + "backend/search/http/__init__.py", + "backend/search/http/body_limit.py", + "backend/search/http/responses.py", + "backend/search/http/schemas.py", + "backend/search/infrastructure/__init__.py", + "backend/search/infrastructure/executor.py", + "backend/search/infrastructure/runtime_entry.py", + "backend/search_bootstrap.py", + "backend/search_browse.py", + "backend/search_candidates.py", + "backend/search_data_selector.py", + "backend/search_execution.py", + "backend/search_filters.py", + "backend/search_indexes.py", + "backend/search_matching.py", + "backend/search_projection.py", + "backend/search_runtime_entry.py", + "backend/search_term_candidates.py", + "backend/search_transport.py", + "backend/search_words.py", + "backend/seo.py", + "backend/shared/__init__.py", + "backend/shared/cache/__init__.py", + "backend/shared/cache/core.py", + "backend/shared/transport/__init__.py", + "backend/shared/transport/streams.py", + "backend/shared/transport/upstream.py", + "backend/site/__init__.py", + "backend/site/application/__init__.py", + "backend/site/application/bootstrap.py", + "backend/site/application/seo.py", + "backend/site/http/__init__.py", + "backend/site/http/responses.py", + "backend/upstream_http.py" ], "pythonVersion": "3.11", "typeCheckingMode": "strict" diff --git a/quality/backend-path-migration.json b/quality/backend-path-migration.json new file mode 100644 index 0000000000000000000000000000000000000000..ffa5ef4cabf2bf02fc420d94f48fae431c663f23 --- /dev/null +++ b/quality/backend-path-migration.json @@ -0,0 +1,593 @@ +{ + "version": 1, + "moves": { + "backend/cache_core.py": "backend/shared/cache/core.py", + "backend/data_formats.py": "backend/search/corpus/domain/formats.py", + "backend/download_warm.py": "backend/download/application/warming.py", + "backend/folder_contents.py": "backend/search/corpus/domain/folder_contents.py", + "backend/folder_tree.py": "backend/search/corpus/domain/folder_tree.py", + "backend/proxy_streams.py": "backend/shared/transport/streams.py", + "backend/reader_archive.py": "backend/reader/archive/domain/validation.py", + "backend/reader_assets.py": "backend/reader/catalog/domain/assets.py", + "backend/reader_index.py": "backend/reader/catalog/domain/index.py", + "backend/reader_ocr.py": "backend/reader/query/domain/ocr.py", + "backend/reader_range_cache.py": "backend/reader/document/domain/range_cache.py", + "backend/reader_v3_catalog.py": "backend/reader/catalog/infrastructure/v3.py", + "backend/record_metadata.py": "backend/search/corpus/domain/records.py", + "backend/search_bootstrap.py": "backend/search/application/bootstrap.py", + "backend/search_browse.py": "backend/search/domain/browse.py", + "backend/search_candidates.py": "backend/search/domain/candidates.py", + "backend/search_data_selector.py": "backend/search/corpus/infrastructure/selection.py", + "backend/search_execution.py": "backend/search/infrastructure/executor.py", + "backend/search_filters.py": "backend/search/domain/filters.py", + "backend/search_indexes.py": "backend/search/corpus/infrastructure/indexes.py", + "backend/search_matching.py": "backend/search/domain/matching.py", + "backend/search_runtime_entry.py": "backend/search/infrastructure/runtime_entry.py", + "backend/search_term_candidates.py": "backend/search/domain/term_candidates.py", + "backend/search_transport.py": "backend/search/http/body_limit.py", + "backend/search_words.py": "backend/search/corpus/domain/words.py", + "backend/seo.py": "backend/site/application/seo.py", + "backend/upstream_http.py": "backend/shared/transport/upstream.py" + }, + "sources": { + "backend/app.py": { + "target": "backend/app.py", + "before_sha256": "85fba717fd43b1283ea51521c3e01b2e29ecf0c0b4d37664cd91822ce2b4a469", + "after_sha256": "c428db5c7aecc19b123ef149ef3725bab8551440b31fdcca7f0e6b5de1008e8d", + "imports": [ + [ + 34, + "from backend.cache_core import cached as _bounded_cache\n", + "from backend.shared.cache.core import cached as _bounded_cache\n" + ], + [ + 48, + "from backend.download_warm import (warm_download_connection as _warm_download_connection,\n", + "from backend.download.application.warming import (warm_download_connection as _warm_download_connection,\n" + ], + [ + 50, + "from backend.folder_tree import build_folder_tree as _build_folder_tree\n", + "from backend.search.corpus.domain.folder_tree import build_folder_tree as _build_folder_tree\n" + ], + [ + 51, + "from backend.folder_contents import get_folder_contents as _get_folder_contents\n", + "from backend.search.corpus.domain.folder_contents import get_folder_contents as _get_folder_contents\n" + ], + [ + 52, + "from backend.search_bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results\n", + "from backend.search.application.bootstrap import build_initial_payload as _build_initial_payload, trim_initial_results as _trim_initial_results\n" + ], + [ + 53, + "from backend.search_candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates\n", + "from backend.search.domain.candidates import literal_candidates as _literal_candidates, wildcard_literal_candidates as _wildcard_literal_candidates\n" + ], + [ + 54, + "from backend.search_browse import browse_order as _browse_order\n", + "from backend.search.domain.browse import browse_order as _browse_order\n" + ], + [ + 55, + "from backend.search_term_candidates import term_candidates as _search_term_candidates\n", + "from backend.search.domain.term_candidates import term_candidates as _search_term_candidates\n" + ], + [ + 56, + "from backend.search_projection import public_record as _public_record, trim_results as _trim_results\n", + "from backend.search.domain.projection import public_record as _public_record, trim_results as _trim_results\n" + ], + [ + 57, + "from backend.reader_identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,\n", + "from backend.reader.query.domain.identity import (READER_ESCAPE_NORMALIZATION_RE as READER_ESCAPE_NORMALIZATION_RE,\n" + ], + [ + 59, + "from backend.reader_index import ReaderIndexBuild, advance_build, new_build\n", + "from backend.reader.catalog.domain.index import ReaderIndexBuild, advance_build, new_build\n" + ], + [ + 77, + "from backend.reader_ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,\n", + "from backend.reader.query.domain.ocr import (OcrPage, fold_reader_ocr_text as fold_reader_ocr_text,\n" + ], + [ + 79, + "from backend.search_filters import (apply_filters as _apply_filters,\n", + "from backend.search.domain.filters import (apply_filters as _apply_filters,\n" + ], + [ + 82, + "from backend.search_words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index,\n", + "from backend.search.corpus.domain.words import (build_vocab_by_len as _build_vocab_by_len, build_word_index as _build_word_index,\n" + ], + [ + 85, + "from backend.search_matching import (compile_exact_matcher as compile_exact_matcher,\n", + "from backend.search.domain.matching import (compile_exact_matcher as compile_exact_matcher,\n" + ], + [ + 88, + "from backend.proxy_streams import (\n", + "from backend.shared.transport.streams import (\n" + ], + [ + 91, + "from backend.reader_range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,\n", + "from backend.reader.document.domain.range_cache import (RangeCacheState as _RangeCacheState, cached_subrange as _cached_reader_subrange,\n" + ], + [ + 109, + "from backend.search_execution import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelled\n", + "from backend.search.infrastructure.executor import SearchBusy as SearchBusy, SearchExecutor, check_search_cancelled\n" + ], + [ + 134, + "from backend.search_transport import SearchBodyLimitMiddleware\n", + "from backend.search.http.body_limit import SearchBodyLimitMiddleware\n" + ], + [ + 135, + "from backend.search_indexes import (\n", + "from backend.search.corpus.infrastructure.indexes import (\n" + ], + [ + 141, + "from backend.reader_assets import (\n", + "from backend.reader.catalog.domain.assets import (\n" + ], + [ + 144, + "from backend.reader_v3_catalog import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecar\n", + "from backend.reader.catalog.infrastructure.v3 import decode_in_thread, load_reading_catalog, merge_sidecar as merge_v3_sidecar\n" + ], + [ + 145, + "from backend.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell\n", + "from backend.site.application.seo import CatalogRecord, CatalogResult, build_catalog as build_seo_catalog, enrich_search_shell\n" + ], + [ + 146, + "from backend.data_formats import (\n", + "from backend.search.corpus.domain.formats import (\n" + ], + [ + 151, + "from backend.record_metadata import (\n", + "from backend.search.corpus.domain.records import (\n" + ], + [ + 159, + "from backend.upstream_http import (\n", + "from backend.shared.transport.upstream import (\n" + ] + ] + }, + "backend/cache_core.py": { + "target": "backend/shared/cache/core.py", + "before_sha256": "59e791dcc6f7283c8076b4e3b22fca020ac7b6cc913686f3f3aa2bf6ed19cc49", + "after_sha256": "59e791dcc6f7283c8076b4e3b22fca020ac7b6cc913686f3f3aa2bf6ed19cc49", + "imports": [], + "compatibility_sha256": "5db4764a36674c28c267f51d9c79f070dcb9ce82195fd321d1792fcd2fc81a59" + }, + "backend/data_formats.py": { + "target": "backend/search/corpus/domain/formats.py", + "before_sha256": "8a24ba52d935bdaa182534c939448ba849527a8d04bb1890648a70cdd47ccfa0", + "after_sha256": "8a24ba52d935bdaa182534c939448ba849527a8d04bb1890648a70cdd47ccfa0", + "imports": [], + "compatibility_sha256": "0fa3da70ad21cbd67e65ccf74a785d24f3308e952494fafb0717b7ec39b42814" + }, + "backend/download_warm.py": { + "target": "backend/download/application/warming.py", + "before_sha256": "b720d87c5fb86d2cac1fb1fc2c7933477e106af7689fff56e6217c446604ab6a", + "after_sha256": "b720d87c5fb86d2cac1fb1fc2c7933477e106af7689fff56e6217c446604ab6a", + "imports": [], + "compatibility_sha256": "a564d9e7980670cd3bfae86424fd70a5d2f38622fe4e56917c0df2a6ae67846b" + }, + "backend/folder_contents.py": { + "target": "backend/search/corpus/domain/folder_contents.py", + "before_sha256": "931758f2f2b76b4cbe51a00b3a5f408c48d9b4e42104476ee21cdd49a083b56d", + "after_sha256": "931758f2f2b76b4cbe51a00b3a5f408c48d9b4e42104476ee21cdd49a083b56d", + "imports": [], + "compatibility_sha256": "6732394438c023e5afdfb5a611b000200b28f75096791525d2ee0e7322e6bd77" + }, + "backend/folder_tree.py": { + "target": "backend/search/corpus/domain/folder_tree.py", + "before_sha256": "95d04cfe5ad79e1cbe6218edeba4567c001f7961f199cfd04363123a1e391fd3", + "after_sha256": "95d04cfe5ad79e1cbe6218edeba4567c001f7961f199cfd04363123a1e391fd3", + "imports": [], + "compatibility_sha256": "6e27cf2b5bb232547b7642b255c77716609e95946a95dbf2e34fc9ef9194b33b" + }, + "backend/proxy_streams.py": { + "target": "backend/shared/transport/streams.py", + "before_sha256": "02c6df15f5058d322042f99b1e8cd454380b5059c7ac9815cddf49bbf3296d6a", + "after_sha256": "02c6df15f5058d322042f99b1e8cd454380b5059c7ac9815cddf49bbf3296d6a", + "imports": [], + "compatibility_sha256": "9cbe5c456e3734e3d6f341229df1f83012e010e2fe1df5e2a2e3cf3fe0f05bcb" + }, + "backend/reader_archive.py": { + "target": "backend/reader/archive/domain/validation.py", + "before_sha256": "9439528bdad3127c8c794489a7edbf940d7cac9a7341e7bc6e2ca09c2751bb24", + "after_sha256": "9439528bdad3127c8c794489a7edbf940d7cac9a7341e7bc6e2ca09c2751bb24", + "imports": [], + "compatibility_sha256": "2e7731076e3f1baa38aab5c684d40f6f4324f016b5a6e7f3e7de6a1f64e1cf14" + }, + "backend/reader_assets.py": { + "target": "backend/reader/catalog/domain/assets.py", + "before_sha256": "a29b7ba7510fa0aec60560f241a5e56700e342e04acb2fb62b9880aa4ef9285d", + "after_sha256": "beb8d1d65c6087c6b8845efdf0fbd11860710ce76189389e2c7edbc7901e92b6", + "imports": [ + [ + 10, + "from backend.upstream_http import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/tests\n", + "from backend.shared.transport.upstream import READER_ASSET_PATH_RE as READER_ASSET_PATH_RE # re-exported for app/tests\n" + ] + ], + "compatibility_sha256": "8a8c3164eec0bb3e9d695ea6be1e620d086fb8c45244e7c9a0d48387ee3f4eab" + }, + "backend/reader_index.py": { + "target": "backend/reader/catalog/domain/index.py", + "before_sha256": "902ac199cc253397475e6fef002b9e718e7b7b92d312847d1bbdd702eb197308", + "after_sha256": "902ac199cc253397475e6fef002b9e718e7b7b92d312847d1bbdd702eb197308", + "imports": [], + "compatibility_sha256": "0942a97313770fd966a5d8a8014faeb6f8d3c1a90d33140d884e0d0fe983c678" + }, + "backend/reader_ocr.py": { + "target": "backend/reader/query/domain/ocr.py", + "before_sha256": "f118914a9ceadb1fa9f7cbe9b83588b1118e4e0225be5704cc2afed978c771e5", + "after_sha256": "f118914a9ceadb1fa9f7cbe9b83588b1118e4e0225be5704cc2afed978c771e5", + "imports": [], + "compatibility_sha256": "17f44f5a4ad4f5dd2a45f570d3cffba4cb090b1fc4047a0b36243c2dceadcef8" + }, + "backend/reader_range_cache.py": { + "target": "backend/reader/document/domain/range_cache.py", + "before_sha256": "966395157c044f254d0c0734231b6af55f1c63bb32e250ff037b644438a68367", + "after_sha256": "966395157c044f254d0c0734231b6af55f1c63bb32e250ff037b644438a68367", + "imports": [], + "compatibility_sha256": "16f6e845acdcb503b4d5e28226f8349281837b04f5cb534de39589df047f4d95" + }, + "backend/reader_v3_catalog.py": { + "target": "backend/reader/catalog/infrastructure/v3.py", + "before_sha256": "114424d45ebf5c45b9c28a24f0d09bca3e72fc97349b81bef58d9e4d028dde41", + "after_sha256": "9d37e1671d7c77888d0b5cd7147d01b7e0c37bb538f019dcc460b95599ab0930", + "imports": [ + [ + 10, + "from backend.upstream_http import open_download_response, validate_fixed_source_redirect_url\n", + "from backend.shared.transport.upstream import open_download_response, validate_fixed_source_redirect_url\n" + ], + [ + 29, + " from backend.reader_assets import READER_BUCKET_PATH_RE\n", + " from backend.reader.catalog.domain.assets import READER_BUCKET_PATH_RE\n" + ], + [ + 150, + " from backend.reader_assets import decode_reader_assets\n", + " from backend.reader.catalog.domain.assets import decode_reader_assets\n" + ] + ], + "compatibility_sha256": "a0f51ed6f25cd6736f13ee4bc9f42b311ab5098d4d7927f2728c25f5a8d82975" + }, + "backend/record_metadata.py": { + "target": "backend/search/corpus/domain/records.py", + "before_sha256": "ba20520ce9a73cb4cebac0b0868678bc5fded004d58f91b4cf8dcb26534f0ce8", + "after_sha256": "ba20520ce9a73cb4cebac0b0868678bc5fded004d58f91b4cf8dcb26534f0ce8", + "imports": [], + "compatibility_sha256": "1a481d9836cfe52b53a7ee6099f6975a236cbc44eb105f684713ad531dbd15c6" + }, + "backend/search_bootstrap.py": { + "target": "backend/search/application/bootstrap.py", + "before_sha256": "41fd419e58c036b00f35bc2e8c8fee12e757f748ef69b56560c2b059addfa24d", + "after_sha256": "41fd419e58c036b00f35bc2e8c8fee12e757f748ef69b56560c2b059addfa24d", + "imports": [], + "compatibility_sha256": "cf0bdda86a58726d5b612c443befcd649875de2078fbd4842328f45b5948e846" + }, + "backend/search_browse.py": { + "target": "backend/search/domain/browse.py", + "before_sha256": "78a1f1d3217e3d6b83573a1d311222cd9d1f66d735d10dc8c96bcee5bda92fa1", + "after_sha256": "78a1f1d3217e3d6b83573a1d311222cd9d1f66d735d10dc8c96bcee5bda92fa1", + "imports": [], + "compatibility_sha256": "a3b2a9d7ffb3453bf45cadbb94cc1c4759bb203a1c613e46c154dad5b4842873" + }, + "backend/search_candidates.py": { + "target": "backend/search/domain/candidates.py", + "before_sha256": "c311bd8a5b0c0897507c99fe8a72913d05e2d54cfaeec537c29a0eceadfa16f4", + "after_sha256": "7b362b32e583cf9052eb052ebc154e109d4c26cc51651c2479a478bf47fbcca5", + "imports": [ + [ + 6, + "from backend.search_indexes import Posting, PostingIndex\n", + "from backend.search.corpus.infrastructure.indexes import Posting, PostingIndex\n" + ] + ], + "compatibility_sha256": "67d284f9d96d274b1b825020d295779c53b3f4f53aadf5e7a524f69a1e0ef81e" + }, + "backend/search_data_selector.py": { + "target": "backend/search/corpus/infrastructure/selection.py", + "before_sha256": "b534cd628f7d02b6e7eccb10d4d850dd8bf3929ebc76d58d744d54ac74e389f5", + "after_sha256": "aa31d23f8a484569c76249afbc59009ae5a29fcdc92d4728f9067f15ba85b00a", + "imports": [ + [ + 19, + "from .search_indexes import load_ngram_index, load_word_index\n", + "from backend.search.corpus.infrastructure.indexes import load_ngram_index, load_word_index\n" + ] + ], + "compatibility_sha256": "0030ffc6de9a61433f45038ecff2a549c4c5cf428633d249fb692db987f82625" + }, + "backend/search_execution.py": { + "target": "backend/search/infrastructure/executor.py", + "before_sha256": "e30bc01eba1cbf8b13c9cd7ce6165c9fe5165ea6523d93104ade88d5fcc80eec", + "after_sha256": "282ccc3aeb661e977e0c029ca2060412d8af8ffb3586048ef298a14550fa4442", + "imports": [], + "logger_identity": [12, "logger = logging.getLogger(__name__)\n", "logger = logging.getLogger(\"backend.search_execution\")\n"], + "compatibility_sha256": "0fd0714b7c11856c3716dcff86cdac92549b583649224ac9ce70a409a4a38042" + }, + "backend/search_filters.py": { + "target": "backend/search/domain/filters.py", + "before_sha256": "a036da20116e665768ef5046bf2cb9395c647466683dbd27b0317a8ca33a61d1", + "after_sha256": "a036da20116e665768ef5046bf2cb9395c647466683dbd27b0317a8ca33a61d1", + "imports": [], + "compatibility_sha256": "be4ce646e0e6611c778b5175454741f77320c168cf430acc22cf6663e3a3fd55" + }, + "backend/search_indexes.py": { + "target": "backend/search/corpus/infrastructure/indexes.py", + "before_sha256": "95d1c3fd9e41c0bb1cc875f349c611033fea50eb848b5b4ae2fb39bdc2cdeba5", + "after_sha256": "95d1c3fd9e41c0bb1cc875f349c611033fea50eb848b5b4ae2fb39bdc2cdeba5", + "imports": [], + "compatibility_sha256": "1f8e884181c9040bf96cba3314601835e67689530073d3e9cf320b31319095c1" + }, + "backend/search_matching.py": { + "target": "backend/search/domain/matching.py", + "before_sha256": "f90a1fe6d6f690125b5148810f8c1429b4a47dd4cfe85913da66b47cb45c17c6", + "after_sha256": "f90a1fe6d6f690125b5148810f8c1429b4a47dd4cfe85913da66b47cb45c17c6", + "imports": [], + "compatibility_sha256": "daf96b7a8b22d50dcef6c6a718b0d13be4ad5bbd310e1f93439d1be7ffd20a10" + }, + "backend/search_runtime_entry.py": { + "target": "backend/search/infrastructure/runtime_entry.py", + "before_sha256": "cfc779c6d743180702b077484ff2f4274620a396a050f657fdcd3724b867f3ec", + "after_sha256": "e757edea706ab1cbb7f90b268c2c1ad797541732938256ef3ecd66be36e4794a", + "imports": [ + [ + 20, + "from .search_data_selector import inspect_generation\n", + "from backend.search.corpus.infrastructure.selection import inspect_generation\n" + ], + [ + 29, + " from . import app as service\n", + " from backend import app as service\n" + ] + ], + "compatibility_sha256": "93998aa3d35d656809b1b158b7e01134a7a3b84801c612ba77f60f70bdf00812" + }, + "backend/search_term_candidates.py": { + "target": "backend/search/domain/term_candidates.py", + "before_sha256": "dc2251331033e4787f7a4edabdf8de6351b85b1c160fbf1b0392734ada9babbf", + "after_sha256": "f639067809a4dc896676a4c471ca9676140130729f3eb324d3d89ad2fef1839c", + "imports": [ + [ + 7, + "from backend.search_execution import check_search_cancelled\n", + "from backend.search.infrastructure.executor import check_search_cancelled\n" + ] + ], + "compatibility_sha256": "609bad5a1ce1e6e5264469aab931f3bf529afedb2210cbc89981d8194397120d" + }, + "backend/search_transport.py": { + "target": "backend/search/http/body_limit.py", + "before_sha256": "9c46e4c4fc1803ab3ff976b1694c27510fb92e2ed162043bf7495d8900c87ad1", + "after_sha256": "9c46e4c4fc1803ab3ff976b1694c27510fb92e2ed162043bf7495d8900c87ad1", + "imports": [], + "compatibility_sha256": "e6a523fe533d1a36a739fcf27ecac591f42a93e4c7fe0c2824fe3e4c7c41276d" + }, + "backend/search_words.py": { + "target": "backend/search/corpus/domain/words.py", + "before_sha256": "77f923765a7726bf3f970d53a00f0d5d91c8dbe27a4ab5278067c07cc19edf40", + "after_sha256": "77f923765a7726bf3f970d53a00f0d5d91c8dbe27a4ab5278067c07cc19edf40", + "imports": [], + "compatibility_sha256": "94e90140e26775005fbee4c8875acc955f753006b90ae2a46ccfd3c14966df4d" + }, + "backend/seo.py": { + "target": "backend/site/application/seo.py", + "before_sha256": "b263f903ae185449ee0e0c375a4d7529420ab673f9d9ceb2772d65d8b7a84615", + "after_sha256": "b263f903ae185449ee0e0c375a4d7529420ab673f9d9ceb2772d65d8b7a84615", + "imports": [], + "compatibility_sha256": "213dcdac9be85cfc41a0390590ce439f27667f7f7f47e988d942cd45ec0d0fa9" + }, + "backend/upstream_http.py": { + "target": "backend/shared/transport/upstream.py", + "before_sha256": "73f6bb9dda28ab2822c19e9810c67b1efe053bcd52c0d4af269e2d240a261374", + "after_sha256": "73f6bb9dda28ab2822c19e9810c67b1efe053bcd52c0d4af269e2d240a261374", + "imports": [], + "compatibility_sha256": "fcf38bc5dfa6b74eb3b0cf48f11d74f31b5334008e8aac01f47c970ea9c4c749" + }, + "backend/download/http/routes.py": { + "target": "backend/download/http/routes.py", + "before_sha256": "c03285f27a7a7d48f0debb58a1f7a69c4727f484e81a5449cce1be94aaffdb4a", + "after_sha256": "d64962afa4c281b3b5262b4d214db1d57e84bd245a5ec50f2b89042717be5ff9", + "imports": [ + [ + 13, + "from backend.proxy_streams import OwnedStreamingResponse, UpstreamLease\n", + "from backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLease\n" + ] + ] + }, + "backend/reader/archive/domain/content.py": { + "target": "backend/reader/archive/domain/content.py", + "before_sha256": "d659bcdfbaa203134134ef15bab2209ffaed3d20877a110f4a850595ba151eba", + "after_sha256": "7e3d6e005e602a2a38635790f8b40f756b537a2d26aee0616a0e23480c3c4793", + "imports": [ + [ + 9, + "from backend.reader_archive import (\n", + "from backend.reader.archive.domain.validation import (\n" + ] + ] + }, + "backend/reader/catalog/application/indexes.py": { + "target": "backend/reader/catalog/application/indexes.py", + "before_sha256": "068f429a5db272fab30a354f86790c5fc4f867a211a0b68364b16305dedd8464", + "after_sha256": "f8970d5cd56401f20ca149dcd3a3830d3b84aedbe08d580cde03a01ba34dd219", + "imports": [ + [ + 10, + "from backend.reader_index import ReaderIndexBuild\n", + "from backend.reader.catalog.domain.index import ReaderIndexBuild\n" + ], + [ + 11, + "from backend.search_execution import SearchBusy, SearchExecutor\n", + "from backend.search.infrastructure.executor import SearchBusy, SearchExecutor\n" + ] + ] + }, + "backend/reader/document/application/ranges.py": { + "target": "backend/reader/document/application/ranges.py", + "before_sha256": "ce7699789839bd9e528c6a618922033e3afa862b429131d929e76f7c4fe2fca2", + "after_sha256": "8cd1016896239d5b1ea662a1fa895de0d0459bb501c7486c3040911ddd39c4d5", + "imports": [ + [ + 10, + "from backend.proxy_streams import OwnedStreamingResponse, SharedRangeFlight\n", + "from backend.shared.transport.streams import OwnedStreamingResponse, SharedRangeFlight\n" + ] + ] + }, + "backend/reader/document/domain/policy.py": { + "target": "backend/reader/document/domain/policy.py", + "before_sha256": "2c08fa0c7e3f7bdb2789b59f46be5de83f1734d23cdeb3373109dd65feea0ab8", + "after_sha256": "a3a28804f9a2c75c7c2a42e442b646f3d20b17023a13eaf1f8fea9bb96c010b9", + "imports": [ + [ + 5, + "from backend.reader_range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry\n", + "from backend.reader.document.domain.range_cache import RangeKey as RangeKey, RangeCacheEntry as RangeCacheEntry\n" + ] + ] + }, + "backend/reader/document/http/transport.py": { + "target": "backend/reader/document/http/transport.py", + "before_sha256": "32b9de3695a5818e0ba0f5b7b85ae413213d2e8ba8d3b51f27eb42aaa4367d22", + "after_sha256": "baec6b7668f3a1d9c24770df998b1b21607719fabb2ed079c776616a21e1ace9", + "imports": [ + [ + 16, + "from backend.proxy_streams import OwnedStreamingResponse, UpstreamLease\n", + "from backend.shared.transport.streams import OwnedStreamingResponse, UpstreamLease\n" + ], + [ + 17, + "from backend.reader_range_cache import RangeCacheState\n", + "from backend.reader.document.domain.range_cache import RangeCacheState\n" + ] + ] + }, + "backend/reader/query/application/ocr.py": { + "target": "backend/reader/query/application/ocr.py", + "before_sha256": "503293eed411290fec33975d2c01557881e9aecb179fedb2b35994dfcdd12765", + "after_sha256": "e074ec39d41385902aa5c6424422bd8ea9d3b80da75fe657d5101619df262532", + "imports": [ + [ + 8, + "from backend.reader_ocr import OcrPage, OcrSearchHit\n", + "from backend.reader.query.domain.ocr import OcrPage, OcrSearchHit\n" + ] + ] + }, + "backend/runtime/application/lifecycle.py": { + "target": "backend/runtime/application/lifecycle.py", + "before_sha256": "b978655e8fed6df094fda0aa97c65d9885ebbf26ab36b4a5d48327437c874de5", + "after_sha256": "2576f91adbecd4fd0cbe97fac21eaa2899ef25f0ca4bc2aedaa04293c9d4a171", + "imports": [ + [ + 12, + "from backend.reader_range_cache import RangeCacheState\n", + "from backend.reader.document.domain.range_cache import RangeCacheState\n" + ], + [ + 13, + "from backend.search_execution import SearchExecutor\n", + "from backend.search.infrastructure.executor import SearchExecutor\n" + ] + ] + }, + "backend/search/domain/ordering.py": { + "target": "backend/search/domain/ordering.py", + "before_sha256": "d475392f7c4e8af1a9a2638e59b175e4add90405f91a8a8cc091e1d4c06b007c", + "after_sha256": "62b034d2318e425166ece79a468a952721e625fee86864c253abcb1184ddaaa8", + "imports": [ + [ + 13, + "from backend.search_browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilter\n", + "from backend.search.domain.browse import MixedCandidates, MixedFilter, MixedRecordFilter, RecordFilter as BrowseRecordFilter\n" + ], + [ + 14, + "from backend.search_indexes import Posting\n", + "from backend.search.corpus.infrastructure.indexes import Posting\n" + ] + ] + }, + "backend/search/http/responses.py": { + "target": "backend/search/http/responses.py", + "before_sha256": "24e5031422b6876b02e3f312c2981083f62611829f85a87ec6ecf8d650b408ae", + "after_sha256": "3a8fb8685d723e1cee5bf2b9214ba90a1df96f07b67db4059e0779d33757f7ef", + "imports": [ + [ + 17, + "from backend.search_execution import SearchBusy\n", + "from backend.search.infrastructure.executor import SearchBusy\n" + ] + ] + }, + "backend/search/corpus/application/preparation.py": { + "target": "backend/search/corpus/application/preparation.py", + "before_sha256": "cc2a0abefb282fdfab0e217f7ea78483de809da27b354bf58d524adb42bb7a76", + "after_sha256": "14e7667035faf0f5d71cc05175264ae217e64a21842c98d9a317a1db6e5655e1", + "imports": [ + [ + 11, + "from backend.data_formats import CompactTreeNode, CompactBrowserEntry\n", + "from backend.search.corpus.domain.formats import CompactTreeNode, CompactBrowserEntry\n" + ], + [ + 12, + "from backend.search_indexes import PostingIndex\n", + "from backend.search.corpus.infrastructure.indexes import PostingIndex\n" + ] + ] + }, + "backend/site/application/bootstrap.py": { + "target": "backend/site/application/bootstrap.py", + "before_sha256": "d4bfc366b5eac6eae82edac65e20e8fc5f3331090c76e7b25b6be983ec3973e6", + "after_sha256": "418e2acdf2b3ed7735de1096b7dc6c28709c5f4d9e5cef85a6a9836232d0bdcc", + "imports": [ + [ + 9, + "from backend.seo import CatalogResult\n", + "from backend.site.application.seo import CatalogResult\n" + ] + ] + }, + "backend/site/http/responses.py": { + "target": "backend/site/http/responses.py", + "before_sha256": "712142fa7c7bc840f44301ae382b1b5b92053de41010a2fb17267fa65c5ba8c9", + "after_sha256": "c66e25bc60bb09f5877326fd14d8fa6b5d11c6cdb8415c484a9347dc043e437e", + "imports": [ + [ + 10, + "from backend.seo import CatalogResult\n", + "from backend.site.application.seo import CatalogResult\n" + ] + ] + } + } +} diff --git a/quality/mutation-reviews/mutation-equivalent-cache-core.json b/quality/mutation-reviews/mutation-equivalent-cache-core.json index a9a952eba354c680758e0539366b60ef268582c2..d64383942719b2dac48c9a7b1d48f8990765bd6e 100644 --- a/quality/mutation-reviews/mutation-equivalent-cache-core.json +++ b/quality/mutation-reviews/mutation-equivalent-cache-core.json @@ -1,6 +1,6 @@ { "tool": "mutmut 3.8.1", - "source": "backend/cache_core.py", + "source": "backend/shared/cache/core.py", "source_sha256": "59e791dcc6f7283c8076b4e3b22fca020ac7b6cc913686f3f3aa2bf6ed19cc49", "equivalent": {} } diff --git a/quality/mutation-reviews/mutation-equivalent-data-formats.json b/quality/mutation-reviews/mutation-equivalent-data-formats.json index 967954c0ebe4fca6ccca765e6a0d488f4d82d812..57a302f4306a884c2382ca83595821a764f65258 100644 --- a/quality/mutation-reviews/mutation-equivalent-data-formats.json +++ b/quality/mutation-reviews/mutation-equivalent-data-formats.json @@ -1,29 +1,29 @@ { "tool": "mutmut 3.8.1", - "source": "backend/data_formats.py", + "source": "backend/search/corpus/domain/formats.py", "source_sha256": "8a24ba52d935bdaa182534c939448ba849527a8d04bb1890648a70cdd47ccfa0", "equivalent": { - "backend.data_formats.x_decode_search_payload__mutmut_3": { + "backend.search.corpus.domain.formats.x_decode_search_payload__mutmut_3": { "sha256": "c6951d627a59938b6585811b64ad2e196537469423d0b953b4139a0b68be2371", "rationale": "typing.cast returns its second argument unchanged; CompactCorpus and None are evaluated as type hints but neither is applied to data at runtime." }, - "backend.data_formats.x_decode_search_payload__mutmut_34": { + "backend.search.corpus.domain.formats.x_decode_search_payload__mutmut_34": { "sha256": "e748938294ba1fce6ccc1779ade46157439a5cf96c56830ccf9da0d7f9d02aee", "rationale": "typing.cast returns raw_item unchanged irrespective of its first argument; list[object] and None have no effect on the decoded record." }, - "backend.data_formats.x_decode_tree_node__mutmut_20": { + "backend.search.corpus.domain.formats.x_decode_tree_node__mutmut_20": { "sha256": "c622274f9e191d799182add121af74b01a99bb3d5a43096dec3f8120e83a703d", "rationale": "The recursive is_root argument changes from False to None. decode_tree_node only tests its truth value when deriving path and isRoot, so either makes the child non-root and is not retained in the output." }, - "backend.data_formats.x_decode_tree_node__mutmut_23": { + "backend.search.corpus.domain.formats.x_decode_tree_node__mutmut_23": { "sha256": "5e04c65ca5d5c8b0ff27e942b10f3f1f74a977096680ae2045ba34a892e1c3ef", "rationale": "Removing the recursive is_root positional argument selects decode_tree_node's own default False, the same value originally supplied." }, - "backend.data_formats.x_decode_folder_tree_data__mutmut_2": { + "backend.search.corpus.domain.formats.x_decode_folder_tree_data__mutmut_2": { "sha256": "1ed43a1586faa962b242cad733260b1985476c9ca48ffc02453c39e583337681", "rationale": "parent_path changes from empty string to None only in a decode_tree_node call with is_root=True. That branch sets path to empty string without inspecting parent_path; all child calls receive that path instead." }, - "backend.data_formats.x_decode_folder_tree_data__mutmut_7": { + "backend.search.corpus.domain.formats.x_decode_folder_tree_data__mutmut_7": { "sha256": "f325f18da7ccfc29bb4998eab690a1a648614775090ee38f239663f5342cf00a", "rationale": "parent_path changes from empty string to XXXX only in a decode_tree_node call with is_root=True. That branch sets path to empty string without inspecting parent_path; all child calls receive that path instead." } diff --git a/quality/mutation-reviews/mutation-equivalent-folder-tree.json b/quality/mutation-reviews/mutation-equivalent-folder-tree.json index 57eeae66e116763385c621a0300a5c1a71d74982..7faa33a0c2111caac83acf50ead122ce63176dd5 100644 --- a/quality/mutation-reviews/mutation-equivalent-folder-tree.json +++ b/quality/mutation-reviews/mutation-equivalent-folder-tree.json @@ -1,58 +1,58 @@ { "tool": "mutmut 3.8.1", - "source": "backend/folder_tree.py", + "source": "backend/search/corpus/domain/folder_tree.py", "source_sha256": "95d04cfe5ad79e1cbe6218edeba4567c001f7961f199cfd04363123a1e391fd3", "scope": "Review covers return values and exceptions for ordinary built-in strings, lists and dicts and integer posting sequences produced by the search index. It excludes custom container side effects, tracing, reflection and intermediate allocation/cost. These survivors are reported as survivors, not killed.", "equivalent": { - "backend.folder_tree.x_build_folder_tree__mutmut_21": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_21": { "sha256": "e194f44320887809a65c506418f7f4c3b9a92cde4d37c6364fe64120cb567cfb", "rationale": "The root's initial hasDirectFiles value is always overwritten in the final node_map loop before the root is returned; the earlier value is never read." }, - "backend.folder_tree.x_build_folder_tree__mutmut_25": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_25": { "sha256": "84893fcb6cf6be064f550d0dd021368b701e7cdf1bc63511d1849a94108becd7", "rationale": "The root's initial hasChildren value is always overwritten from its final child list before showSelfToggle is computed or the root returned." }, - "backend.folder_tree.x_build_folder_tree__mutmut_29": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_29": { "sha256": "6b4c73eca4de4cbd1a4fe020325d913441b502eea73c768f48cf2a0b462a38b2", "rationale": "The root's initial showSelfToggle value is always overwritten in the final node_map loop before return." }, - "backend.folder_tree.x_build_folder_tree__mutmut_47": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_47": { "sha256": "b0796cf9514c13e1e986785501a1b71a4b06f2b7033a644f0c1f9808baaf8972", "rationale": "The extra depth-zero slice joins to the empty key, already present as the root in node_map, so it cannot create or modify a node; subsequent iterations are unchanged. One extra lookup is performed." }, - "backend.folder_tree.x_build_folder_tree__mutmut_51": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_51": { "sha256": "0988345eb3c859739cbbf679e86bd1ff3e727ca611ff9c07f837c6c775925210", "rationale": "The extra final depth slices a built-in list beyond its end and produces the same full path as the previous depth, already inserted in node_map, so no node is created or modified. One extra lookup is performed." }, - "backend.folder_tree.x_build_folder_tree__mutmut_58": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_58": { "sha256": "0ac3bc8bda539ee21308969ab87b22effe37fa1e1f8ecff8502093a57f39b77f", "rationale": "At the only newly enabled depth, depth=1, joining parts[:0] yields the same empty parent key as the original else branch; all greater depths are unchanged." }, - "backend.folder_tree.x_build_folder_tree__mutmut_63": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_63": { "sha256": "18b1f81684d0130e7598e435d567d41b9ba6cee4b9c09996adc09dc41ecbbdb5", "rationale": "The loop starts at depth 1. For depth=1 the newly enabled join of parts[:0] yields the original empty parent key; for larger depths the expression is unchanged." }, - "backend.folder_tree.x_build_folder_tree__mutmut_82": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_82": { "sha256": "a0a124e55f8ba98e6d0cdcf11abf3c2e0018eaaa2f04b09a957d819fb11d5183", "rationale": "Each child node's initial hasDirectFiles value is overwritten in the final node_map loop before it is used to compute showSelfToggle or returned." }, - "backend.folder_tree.x_build_folder_tree__mutmut_86": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_86": { "sha256": "0b004afe481b2a11c575ace2b024c91a3a52f14d1f70b0c0ef7b9f646f62ba63", "rationale": "Each child node's initial hasChildren value is overwritten from its final child list before showSelfToggle is computed or the tree returned." }, - "backend.folder_tree.x_build_folder_tree__mutmut_90": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_90": { "sha256": "4c26ed0581bd2cd9719da7ffed29d23627c6582b2d985bdff4934a76fcad02e2", "rationale": "Each child node's initial showSelfToggle value is overwritten in the final node_map loop before the tree is returned." }, - "backend.folder_tree.x_build_folder_tree__mutmut_105": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_105": { "sha256": "4f08f6ecdd4bac502f7ec507b3c4d515a0435ff64c29014dedc511efd9036f63", "rationale": "typing.cast ignores its first argument and returns the same folder value at runtime." }, - "backend.folder_tree.x_build_folder_tree__mutmut_111": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_111": { "sha256": "89cbb34aa1530cf62d960fe68ec1ec537e9abdae871c70e40fd1b0d8f80e6487", "rationale": "For a missing Folder key, both the empty-list default and None are falsy and become [] in the subsequent or expression; present key values are unchanged." }, - "backend.folder_tree.x_build_folder_tree__mutmut_113": { + "backend.search.corpus.domain.folder_tree.x_build_folder_tree__mutmut_113": { "sha256": "9c5ea233e5727f44d086e98346d89a14c6dcd56df21ba43e33ea0b5d2a5b199d", "rationale": "dict.get without a default returns None. For a missing Folder key it becomes [] in the subsequent or expression; present key values are unchanged." } diff --git a/quality/mutation-reviews/mutation-equivalent-mutation-gate.json b/quality/mutation-reviews/mutation-equivalent-mutation-gate.json index 266183ced49f667b902a82861ed86adaa7a97a84..0c112c44025077f759ffbc2f5facf83cdd12c390 100644 --- a/quality/mutation-reviews/mutation-equivalent-mutation-gate.json +++ b/quality/mutation-reviews/mutation-equivalent-mutation-gate.json @@ -1,7 +1,7 @@ { "tool": "mutmut 3.8.1", "source": "scripts/check_search_words_mutation.py", - "source_sha256": "6fe363e8127d96da0236650b8f407de98ec00529dd981b53ed86b1cbc6c14a21", + "source_sha256": "90eb853e559f0330b1766d7679ffb31d94ce22a5f6ad2a4822c9d19f0ec39b71", "scope": "Only ordinary built-in dicts with built-in string keys and integer values, without concurrent mutation, dict subclasses, tracing, introspection, or monkeypatching. Comparison is the return value and exceptions of mutation_errors. The initial required-field validation is executed unchanged. These survivors remain survivors, not killed.", "equivalent": { "scripts.check_search_words_mutation.x_mutation_errors__mutmut_22": { diff --git a/quality/mutation-reviews/mutation-equivalent-proxy-streams.json b/quality/mutation-reviews/mutation-equivalent-proxy-streams.json index 5b031509e9f1cd4236668e6b70b9593b70498bc7..c4ed3a3cdfc534a2ef975650ee7765168899b27f 100644 --- a/quality/mutation-reviews/mutation-equivalent-proxy-streams.json +++ b/quality/mutation-reviews/mutation-equivalent-proxy-streams.json @@ -1,42 +1,42 @@ { "tool": "mutmut 3.8.1", - "source": "backend/proxy_streams.py", + "source": "backend/shared/transport/streams.py", "source_sha256": "02c6df15f5058d322042f99b1e8cd454380b5059c7ac9815cddf49bbf3296d6a", "scope": "Review is limited to normal Starlette Response headers and production asyncio single-loop ownership in shared_reader_range_response. It excludes replaced/custom headers, monkeypatched Tasks or flight state, external threads directly mutating fields, and internal exception tracing. These survivors remain reported as survivors, never as killed.", "equivalent": { - "backend.proxy_streams.xǁSharedRangeFlightǁ_settled__mutmut_14": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_settled__mutmut_14": { "sha256": "58b13c471e56e9796232b1db9c9508931dc426a654e2ea22aa86e6014f8bad55", "rationale": "A started _run always sets done in its nested finally, even if response cleanup raises. If the Task is cancelled before it starts, _settled observes task.cancelled() and stores a truthy CancelledError before this expression. Thus the RuntimeError fallback is not constructed in normal task ownership. Directly calling _settled with an unrelated task or changing owner state is outside scope." }, - "backend.proxy_streams.xǁSharedRangeFlightǁ_settled__mutmut_15": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_settled__mutmut_15": { "sha256": "8324ed1e793e7a09e4de488be940cc73b45b77ffb687ca5a678448bc70c84fbf", "rationale": "As for _settled mutant 14, normal _run task completion or pre-start cancellation makes the RuntimeError fallback unreachable; changing its message cannot affect ready or the flight state." }, - "backend.proxy_streams.xǁSharedRangeFlightǁ_settled__mutmut_16": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_settled__mutmut_16": { "sha256": "b3e896b68a38154583eea6fd5feeeedfe649fc2055e88b4fe6cfbb3370bf5005", "rationale": "As for _settled mutant 14, normal _run task completion or pre-start cancellation makes the RuntimeError fallback unreachable; uppercasing its message cannot affect ready or the flight state." }, - "backend.proxy_streams.xǁSharedRangeFlightǁ_run__mutmut_5": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_run__mutmut_5": { "sha256": "98e607e44e281dea1a6de1226c1f7fac98074de07fa441a72ae51400778c2884", "rationale": "For a missing content-length, int(None) raises TypeError instead of int('') raising ValueError; both are caught by the same handler and assign -1. A present header is unchanged. Internal exception class and tracing differ." }, - "backend.proxy_streams.xǁSharedRangeFlightǁ_run__mutmut_7": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_run__mutmut_7": { "sha256": "fe88b7a6702276b6d512f90f06f72c198542b1dad5043a2e288b37ee909e9a5e", "rationale": "For standard Starlette headers, get without a default returns None for a missing header. As for _run mutant 5, TypeError instead of ValueError is caught by the same handler and assigns -1; present values are unchanged. Internal exception tracing differs." }, - "backend.proxy_streams.xǁSharedRangeFlightǁ_run__mutmut_9": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_run__mutmut_9": { "sha256": "edce3d28cda7653f28ad79b165b4a48d911da27bc1e2870e1b3ab0727724903a", "rationale": "The production responses use Starlette MutableHeaders, which lowercases lookup keys, so CONTENT-LENGTH and content-length retrieve the same value. A custom case-sensitive headers implementation is outside scope." }, - "backend.proxy_streams.xǁSharedRangeFlightǁ_run__mutmut_10": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_run__mutmut_10": { "sha256": "309bc742a66abfe4f838fbfed15b860f41b23ea22c6314901e581c37c4852368", "rationale": "For a missing header, both int('XXXX') and int('') raise ValueError caught by the same handler, assigning -1; present values are unchanged. The caught exception text and tracing differ." }, - "backend.proxy_streams.xǁSharedRangeFlightǁ_run__mutmut_13": { + "backend.shared.transport.streams.xǁSharedRangeFlightǁ_run__mutmut_13": { "sha256": "3ee6852c949197094d9153aac76c8dfab1c11a03c6a510b4becc54a3e8278fa7", "rationale": "Both -1 and -2 fail the unchanged 0 <= length test for every limit and take the decline path. The local value and tracing differ." }, - "backend.proxy_streams.xǁRangeSubscriptionǁstream__mutmut_11": { + "backend.shared.transport.streams.xǁRangeSubscriptionǁstream__mutmut_11": { "sha256": "987213c637ec785d7bd63c133fc14c8f303915488729f536870c8f5aa8d22753", "rationale": "After the ordinary chunks list is drained and flight.done is checked false, there is no await or yielding operation before standard asyncio.Event.clear and the next condition. On the owning event loop no producer can append a chunk or set done in that interval, so both operands are false and replacing or with and has no effect. Direct cross-thread mutation or custom Event/list side effects are outside scope." } diff --git a/quality/mutation-reviews/mutation-equivalent-reader-archive.json b/quality/mutation-reviews/mutation-equivalent-reader-archive.json index 1e3fc4ee7302e2e1f6068ebed093fa64be2946c3..fe0a589ef2ce1f9e55745f84efbb27a2777ed0fe 100644 --- a/quality/mutation-reviews/mutation-equivalent-reader-archive.json +++ b/quality/mutation-reviews/mutation-equivalent-reader-archive.json @@ -1,14 +1,14 @@ { "tool": "mutmut 3.8.1", - "source": "backend/reader_archive.py", + "source": "backend/reader/archive/domain/validation.py", "source_sha256": "9439528bdad3127c8c794489a7edbf940d7cac9a7341e7bc6e2ca09c2751bb24", "scope": "Reader ZIP validation with caller-owned limits, synthetic end records and directories; equivalent survivors are not killed.", "equivalent": { - "backend.reader_archive.x_validate_reader_archive__mutmut_5": { + "backend.reader.archive.domain.validation.x_validate_reader_archive__mutmut_5": { "sha256": "99f656f9674f6c3f148824d75fd280b6ab730646608a1cb4a6b30ef5017e2c54", "rationale": "typing.cast returns its second argument unchanged at runtime and ignores the first, so cast(None, zipfile) behaves exactly like cast(object, zipfile)." }, - "backend.reader_archive.x_validate_reader_archive__mutmut_230": { + "backend.reader.archive.domain.validation.x_validate_reader_archive__mutmut_230": { "sha256": "8c8201763b3fdb8853d74bdd55d194c0f6b40dba4617f7aded677b466d66b1ac", "rationale": "When header_offset equals len(archive), the next condition header_offset >= central_directory_offset also holds, because central_directory_offset <= len(archive) was verified earlier. The same ReaderArchiveInvalidError with the same message is raised, so > and >= are indistinguishable." } diff --git a/quality/mutation-reviews/mutation-equivalent-reader-index.json b/quality/mutation-reviews/mutation-equivalent-reader-index.json index c68fcbd5300cdd392ce8be22c9f069fdb74fc40e..c4141fbbac5b0476a98f0a67bd6742533c7a6b9c 100644 --- a/quality/mutation-reviews/mutation-equivalent-reader-index.json +++ b/quality/mutation-reviews/mutation-equivalent-reader-index.json @@ -1,21 +1,21 @@ { "tool": "mutmut 3.8.1", - "source": "backend/reader_index.py", + "source": "backend/reader/catalog/domain/index.py", "source_sha256": "902ac199cc253397475e6fef002b9e718e7b7b92d312847d1bbdd702eb197308", "equivalent": { - "backend.reader_index.x_advance_build__mutmut_32": { + "backend.reader.catalog.domain.index.x_advance_build__mutmut_32": { "sha256": "10641363a41f95af50a475e53becf474d745d68f583593978af469471d750006", "rationale": "typing.cast returns the current URL unchanged; replacing the type argument str with None does not affect source ID lookup or publication." }, - "backend.reader_index.x_advance_build__mutmut_91": { + "backend.reader.catalog.domain.index.x_advance_build__mutmut_91": { "sha256": "c230d4a9712f56f289f0514c83f6dea4c5be77aab117b985af023d6e3af8cb73", "rationale": "typing.cast returns the folder list unchanged; replacing list[object] with None does not affect the list validation or alias eligibility." }, - "backend.reader_index.x_advance_build__mutmut_98": { + "backend.reader.catalog.domain.index.x_advance_build__mutmut_98": { "sha256": "ea2c50f7c0f50d328ca21ff4701ce56d4800223decedd7038b5c294427b948fd", "rationale": "typing.cast returns the folder list unchanged; replacing list[str] with None does not affect the joined legacy path." }, - "backend.reader_index.x_advance_build__mutmut_140": { + "backend.reader.catalog.domain.index.x_advance_build__mutmut_140": { "sha256": "68ba945e857c5ab1086218cd3928c4a6ce285e212cb9d1a3ce410f0749f36e81", "rationale": "typing.cast returns the repository unchanged; replacing str with None does not affect the repository index key." } diff --git a/quality/mutation-reviews/mutation-equivalent-record-metadata.json b/quality/mutation-reviews/mutation-equivalent-record-metadata.json index c6087f5505f2c743f75b4d5fe5891df0d3b7647f..31da799617462a71ed12a60976972b05d5d641e8 100644 --- a/quality/mutation-reviews/mutation-equivalent-record-metadata.json +++ b/quality/mutation-reviews/mutation-equivalent-record-metadata.json @@ -1,233 +1,233 @@ { "tool": "mutmut 3.8.1", - "source": "backend/record_metadata.py", + "source": "backend/search/corpus/domain/records.py", "source_sha256": "ba20520ce9a73cb4cebac0b0868678bc5fded004d58f91b4cf8dcb26534f0ce8", "equivalent": { - "backend.record_metadata.x_build_record_relative_path__mutmut_2": { + "backend.search.corpus.domain.records.x_build_record_relative_path__mutmut_2": { "sha256": "6d8e7727cb6e6e9445d727d0ec1d3388fbcdcaa72337f82612a06b2ff5919ffb", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_build_record_relative_path__mutmut_15": { + "backend.search.corpus.domain.records.x_build_record_relative_path__mutmut_15": { "sha256": "a8ccc474703aad9f0b9a07d9dd82cb1591e26e0824c86b0205db7e23802fc381", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_build_record_relative_path__mutmut_31": { + "backend.search.corpus.domain.records.x_build_record_relative_path__mutmut_31": { "sha256": "c9d49bcb78f45381c868a0a155abe4d61a720a4a968c6d816853c784b7451774", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_dataset_file_url__mutmut_6": { + "backend.search.corpus.domain.records.x_dataset_file_url__mutmut_6": { "sha256": "a60677cbe14ba2b7169c2b6db821d35fc52db2eda61a57c58c8579e3f1c522df", "rationale": "urllib.parse.quote defaults safe to slash; omitting safe=\"/\" therefore retains identical escaping and separators for every str input." }, - "backend.record_metadata.x_dataset_file_url__mutmut_7": { + "backend.search.corpus.domain.records.x_dataset_file_url__mutmut_7": { "sha256": "469037f3f8e1be5f00b33abe9ca3e53b20a65626503799089151a3ce3afa0328", "rationale": "urllib.parse.quote always leaves ASCII letters unescaped. Adding uppercase X to the existing slash-safe set therefore cannot change URL escaping for str input." }, - "backend.record_metadata.x_dataset_file_urls__mutmut_5": { + "backend.search.corpus.domain.records.x_dataset_file_urls__mutmut_5": { "sha256": "1f40fa9261c6e2b4ef0a6d4b74c7bdf2392f87d286afb903f8220f9ef50cbcb3", "rationale": "urllib.parse.quote defaults safe to slash; omitting safe=\"/\" therefore retains identical escaping and separators for every str input." }, - "backend.record_metadata.x_dataset_file_urls__mutmut_6": { + "backend.search.corpus.domain.records.x_dataset_file_urls__mutmut_6": { "sha256": "61c4fce32f1ad1f8cb9b83111cb96a51f96e7110795cc51b23720c80dd2bcb14", "rationale": "urllib.parse.quote always leaves ASCII letters unescaped. Adding uppercase X to the existing slash-safe set therefore cannot change URL escaping for str input." }, - "backend.record_metadata.x_build_record_link__mutmut_5": { + "backend.search.corpus.domain.records.x_build_record_link__mutmut_5": { "sha256": "b4c149ba35ecab2f2d8ad92c22289007b0bef45e75e01cff35ac3db60fe5c613", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_build_record_path_url__mutmut_7": { + "backend.search.corpus.domain.records.x_build_record_path_url__mutmut_7": { "sha256": "d7e6875c97bd8b180547b3015a96ad3aefdcd4b5fda66c4b57c39664112f265f", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_enrich_browser_entry__mutmut_14": { + "backend.search.corpus.domain.records.x_enrich_browser_entry__mutmut_14": { "sha256": "afeeb5373aee69d44b134f44dbe2e8f7b315c77b853de032d910c30005d8d44b", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_enrich_browser_entry__mutmut_20": { + "backend.search.corpus.domain.records.x_enrich_browser_entry__mutmut_20": { "sha256": "e39c7f25f6dc2ca26f53c31eb18a175a8df37de9594e1b85180a22541fdbeff2", "rationale": "decoded is a plain dict copied from entry. On a missing key the empty list, None, and omitted-default None are all falsy and replaced by the same empty list via or []; present values are identical." }, - "backend.record_metadata.x_enrich_browser_entry__mutmut_22": { + "backend.search.corpus.domain.records.x_enrich_browser_entry__mutmut_22": { "sha256": "00ffbcc630288e5fcdcff244bdb9812a4bc6c2f0ac8891cd0bb9932a0b7dc88f", "rationale": "decoded is a plain dict copied from entry. On a missing key the empty list, None, and omitted-default None are all falsy and replaced by the same empty list via or []; present values are identical." }, - "backend.record_metadata.x_enrich_browser_entry__mutmut_45": { + "backend.search.corpus.domain.records.x_enrich_browser_entry__mutmut_45": { "sha256": "c0f1aa66e597af3bedc7e70189257d1865b988ed404cdfbe938bd9566303c7bc", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_enrich_browser_entry__mutmut_51": { + "backend.search.corpus.domain.records.x_enrich_browser_entry__mutmut_51": { "sha256": "f7468a36e7b485f1c9c25e66be9408f83dd8eb97b6494a5a163d1a536236e815", "rationale": "decoded is a plain dict copied from entry. On a missing key the empty list, None, and omitted-default None are all falsy and replaced by the same empty list via or []; present values are identical." }, - "backend.record_metadata.x_enrich_browser_entry__mutmut_53": { + "backend.search.corpus.domain.records.x_enrich_browser_entry__mutmut_53": { "sha256": "c8cb6c8a11612ce329e812d28e17d1478a0b4792a7dc48d3d2e1893c9e49831c", "rationale": "decoded is a plain dict copied from entry. On a missing key the empty list, None, and omitted-default None are all falsy and replaced by the same empty list via or []; present values are identical." }, - "backend.record_metadata.x_reader_asset_url__mutmut_5": { + "backend.search.corpus.domain.records.x_reader_asset_url__mutmut_5": { "sha256": "16cf7a98dc16d1f2b06aaa8a918cc6e6a7e8613f4d62618ea36b41037d72a975", "rationale": "urllib.parse.quote defaults safe to slash; omitting safe=\"/\" therefore retains identical escaping and separators for every str input." }, - "backend.record_metadata.x_reader_asset_url__mutmut_12": { + "backend.search.corpus.domain.records.x_reader_asset_url__mutmut_12": { "sha256": "331614206fd47c927038dc4e157f7386dab9e47790e43094d7a098abcde32686", "rationale": "urllib.parse.quote always leaves ASCII letters unescaped. Adding uppercase X to the existing slash-safe set therefore cannot change URL escaping for str input." }, - "backend.record_metadata.x_reader_extension_for_asset__mutmut_1": { + "backend.search.corpus.domain.records.x_reader_extension_for_asset__mutmut_1": { "sha256": "4e1b056d8759399e0e619810d0f02acb302dbde76475e82bc7b52b24676aabbd", "rationale": "For e mode, omitted original_extension changes the fallback from empty to XXXX, neither of which belongs to READER_NATIVE_FOLIATE_EXTENSIONS; both select epub. Other modes never use this default." }, - "backend.record_metadata.x_reader_extension_for_asset__mutmut_8": { + "backend.search.corpus.domain.records.x_reader_extension_for_asset__mutmut_8": { "sha256": "9faaba0e832ccbc47445ac78aca2cf6629222eacfc4b9d00e3ab6e3526d50749", "rationale": "When asset p is falsy, both empty string and XXXX are strings that match neither manifest suffix nor ebook filename regex; they give the same mode/original-extension fallback. Truthy paths are unaffected." }, - "backend.record_metadata.x_reader_extension_for_asset__mutmut_45": { + "backend.search.corpus.domain.records.x_reader_extension_for_asset__mutmut_45": { "sha256": "d0f870c1bf0a9b9f5a17250a96a725876f3bafc0da7fe3f6b52fa0d4007cb003", "rationale": "The regex is compiled with re.IGNORECASE; its alphabetic literals and ASCII character ranges denote the same case-insensitive patterns in uppercase and lowercase." }, - "backend.record_metadata.x_reader_extension_for_asset__mutmut_55": { + "backend.search.corpus.domain.records.x_reader_extension_for_asset__mutmut_55": { "sha256": "7e1a7d8e39646543f1ea38e619337fc06603f2261b1e8debc37fe24fbff6baed", "rationale": "If original_extension is falsy, the resulting empty string and xxxx are both absent from READER_NATIVE_FOLIATE_EXTENSIONS, selecting epub. Truthy original extensions are unchanged." }, - "backend.record_metadata.x_reader_extension_for_asset__mutmut_56": { + "backend.search.corpus.domain.records.x_reader_extension_for_asset__mutmut_56": { "sha256": "c1efd02e33c785000dda5fa07f4ec2a21b553b8c5cfb9b739bf4542ad18f89f7", "rationale": "str(...).lower() precedes lstrip: its output cannot contain ASCII uppercase X, so adding X to the dot stripping set cannot change the resulting extension." }, - "backend.record_metadata.x__reader_bucket_url__mutmut_7": { + "backend.search.corpus.domain.records.x__reader_bucket_url__mutmut_7": { "sha256": "ca5b311a481cf52cfa72bb04800586d59bf445986c823110fca6839e3c1153dc", "rationale": "urllib.parse.quote defaults safe to slash; omitting safe=\"/\" therefore retains identical escaping and separators for every str input." }, - "backend.record_metadata.x__reader_bucket_url__mutmut_8": { + "backend.search.corpus.domain.records.x__reader_bucket_url__mutmut_8": { "sha256": "cc3c5a3d95fbcacfc9ffe4af6012f620a27c07253c3b078d5ce3f967016c3fcd", "rationale": "urllib.parse.quote always leaves ASCII letters unescaped. Adding uppercase X to the existing slash-safe set therefore cannot change URL escaping for str input." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_7": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_7": { "sha256": "30a6ce7128905a7769d937863b966a3580dc4947b9d2d3cc0040328fd15a4a29", "rationale": "For falsy o, neither empty string nor XXXX ends in /ocr-manifest.json; no OCR field is produced. Truthy o values are unchanged." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_44": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_44": { "sha256": "c10f4345b86aeb1dc0e688dd3e3f1a8e166ccf71a3372605f2b4e056ed0062f8", "rationale": "If s==3 the following s!=2 guard returns the same OCR fields; if s==4 the mutation returns those fields one guard earlier. All other s values preserve both guard decisions." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_64": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_64": { "sha256": "c0b352d5e71e47eaf4543e548080f35e9c09905e93b14ebf37a10f84f897c5be", "rationale": "str(...).lower() precedes lstrip: its output cannot contain ASCII uppercase X, so adding X to the dot stripping set cannot change the resulting extension." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_112": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_112": { "sha256": "4a1a4f02131cb02a7a592b0eb977f8c2e96a0e5f81b650049b977670c45db78c", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_146": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_146": { "sha256": "20565ea3636c0e13f31bec01d590ceddf4fa4e2f9949d8c3b329ca240fc54b96", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_165": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_165": { "sha256": "47a2297e0c45253385ff3f2a0bd47190afc50374808cd84cbb66c52b724e6dd4", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_186": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_186": { "sha256": "aca78b14ac65ad388c09cff06ba0c16bf83a5aabbb3c760c6a350ab10a98f8f0", "rationale": "urllib.parse.quote defaults safe to slash; omitting safe=\"/\" therefore retains identical escaping and separators for every str input." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_187": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_187": { "sha256": "cbdf9645442be891d1eff2f5959093a0decdb3b784c82eec5023a854f67e2d8a", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_193": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_193": { "sha256": "0ed5f865af4f3e3bde64ef4b556272d0f5d0ea923b5b2cb595c645add373d33b", "rationale": "urllib.parse.quote always leaves ASCII letters unescaped. Adding uppercase X to the existing slash-safe set therefore cannot change URL escaping for str input." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_8": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_8": { "sha256": "b43a7ff6461ef7e29fc3355493d47a0da67cfe0a6bbfa427bcf9656ddf18e0ec", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_25": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_25": { "sha256": "120eadeb1f122eaa10b8939400beed210d988057c2c9b5861ffa25262273d4b8", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_26": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_26": { "sha256": "7480207af869800146eb138d9d17704096ede5a4d8f22ca851b9708dcb3bc15b", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_31": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_31": { "sha256": "2bea2ffc76f71dfbdec797c51195d70e6dc6ce169b26feb26506f7fe8a56aa38", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_32": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_32": { "sha256": "281b24f872c69d4f0008caab75eadd99cf64765c71970d80839bf6e80f027c34", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_37": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_37": { "sha256": "c273a254936b3af83aeecadb0cc2471f8a972a2edd83a74d3e25d77a9c717b99", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_38": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_38": { "sha256": "8df2f91c61c4d3ec4c7aa905fcb4032eb52890093315608f1dcb978f81a55615", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_43": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_43": { "sha256": "41c67ac7d17436fd5b1a3a288323bdb2b3017b6faf03f5094cecb5efd989412e", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_44": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_44": { "sha256": "735ae3dcf4bd408cf227a81a6d508c8ea1798e28a86e1c82dae706d90fa7714f", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_49": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_49": { "sha256": "4b85dc9535fe83437ba891239c3b5b1a5b5f9facce8428e9c88450ac1ae517f8", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_50": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_50": { "sha256": "47fc7236c85350953fdf9d994e76ac3334ee92872c675f657c20f3c462bccac9", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_55": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_55": { "sha256": "02eb9cbfe4f2d85c88f0eb6f23c7ff520037c8f97d2e2d16d720555ef6be54de", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_56": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_56": { "sha256": "59b09e7b450173ec45cdd94f7ff1b3f4e87881d8164449b158e4987cd2a40328", "rationale": "This changes only index 1 of a direct_modes tuple. The sole read uses direct_modes[direct_extension][0], so the modified value is never observed or returned." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_67": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_67": { "sha256": "ff097832d8c239096ce470e5d076506731ccdad97f3346a9e2a927ba371c14d6", "rationale": "For a falsy Extension, the original empty value and mutated xxxx are both absent from direct_modes and neither selects a direct reader; truthy extensions are unchanged." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_68": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_68": { "sha256": "0be43703574ac8eedda046e87ecdd6206cd293aececdb9702cdc67dfbcf0a681", "rationale": "str(...).lower() precedes lstrip: its output cannot contain ASCII uppercase X, so adding X to the dot stripping set cannot change the resulting extension." }, - "backend.record_metadata.x_enrich_reader_record__mutmut_78": { + "backend.search.corpus.domain.records.x_enrich_reader_record__mutmut_78": { "sha256": "fc252768dfd2517eb1db1250dd5b8eae01a0459b0f2b38863a4e9dde837e12ac", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_add_reader_assets__mutmut_2": { + "backend.search.corpus.domain.records.x_add_reader_assets__mutmut_2": { "sha256": "e5ab146b4d3ace0b3a6236e197986b99150f3fd7a4422415f81af110718a734e", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_add_reader_assets__mutmut_23": { + "backend.search.corpus.domain.records.x_add_reader_assets__mutmut_23": { "sha256": "67f02266eed6501ad891e1926a61171baa2fbcf29ab32736ee8a74fe97208cf1", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_reader_resolved_record__mutmut_19": { + "backend.search.corpus.domain.records.x_reader_resolved_record__mutmut_19": { "sha256": "8b233a5269be528f67c1e4e7923b9f6bee81671a4e7c6399b24de2a6ef3f096f", "rationale": "str(...).lower() precedes lstrip: its output cannot contain ASCII uppercase X, so adding X to the dot stripping set cannot change the resulting extension." }, - "backend.record_metadata.x_reader_resolved_record__mutmut_22": { + "backend.search.corpus.domain.records.x_reader_resolved_record__mutmut_22": { "sha256": "769c690733b18765ef0619dfde37b97ea725abeaed6528ecebc0d8b4d9c987ae", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_reader_resolved_record__mutmut_39": { + "backend.search.corpus.domain.records.x_reader_resolved_record__mutmut_39": { "sha256": "0199581854c5712a152baa32ff5ce3a171afa80674822715d0a0ab620a9e9aef", "rationale": "typing.cast returns the supplied value unchanged; replacing only its type expression with None cannot alter the record, URL, fields, or result at runtime." }, - "backend.record_metadata.x_reader_resolved_record__mutmut_76": { + "backend.search.corpus.domain.records.x_reader_resolved_record__mutmut_76": { "sha256": "45b66ee9ec4539d74eccf6940fa5092cd412435011675c6e0d9a966bf13b2682", "rationale": "For a string and positive maxsplit, rsplit(\"/\", maxsplit)[-1] is exactly the suffix after its final slash; omitting maxsplit or changing 1 to 2 leaves that last component unchanged." }, - "backend.record_metadata.x_reader_resolved_record__mutmut_80": { + "backend.search.corpus.domain.records.x_reader_resolved_record__mutmut_80": { "sha256": "8af2f7f13b7c022c8fe2a1d74a390ae9e25c533109a8b59d899fb9cb49058872", "rationale": "For a string and positive maxsplit, rsplit(\"/\", maxsplit)[-1] is exactly the suffix after its final slash; omitting maxsplit or changing 1 to 2 leaves that last component unchanged." }, - "backend.record_metadata.x_reader_asset_fields__mutmut_91": { + "backend.search.corpus.domain.records.x_reader_asset_fields__mutmut_91": { "sha256": "6b5e07ea89db3d95caa152e1e18bc31ae356792e46692c65c63fcd9925cf6661", "rationale": "Every str(original_extension).lower() call returns a builtin lowercase str with no ASCII uppercase X, including when original_extension has a stateful __str__. Consequently lstrip(\"XX.XX\") and lstrip(\".\") produce the same value at that exact evaluation; the preceding test and evaluation count are unchanged." } diff --git a/quality/mutation-reviews/mutation-equivalent-search-bootstrap.json b/quality/mutation-reviews/mutation-equivalent-search-bootstrap.json index 4f3407cb0f765310aa8cf1a1d948749673ebf419..80886a7dd5c9f8341a03d0c52229d7658ccfb043 100644 --- a/quality/mutation-reviews/mutation-equivalent-search-bootstrap.json +++ b/quality/mutation-reviews/mutation-equivalent-search-bootstrap.json @@ -1,6 +1,6 @@ { "tool": "mutmut 3.8.1", - "source": "backend/search_bootstrap.py", + "source": "backend/search/application/bootstrap.py", "source_sha256": "41fd419e58c036b00f35bc2e8c8fee12e757f748ef69b56560c2b059addfa24d", "scope": "Initial payload fields and ordering with ordinary built-in records and dynamically supplied callbacks; equivalent survivors are not killed.", "equivalent": {} diff --git a/quality/mutation-reviews/mutation-equivalent-search-browse.json b/quality/mutation-reviews/mutation-equivalent-search-browse.json index ed6b0a6fc7cfb2fb70c11b6af8ce058f31aa88ec..db599523bc6ebdc0148e0b401aaaf5297e120fbe 100644 --- a/quality/mutation-reviews/mutation-equivalent-search-browse.json +++ b/quality/mutation-reviews/mutation-equivalent-search-browse.json @@ -1,6 +1,6 @@ { "tool": "mutmut 3.8.1", - "source": "backend/search_browse.py", + "source": "backend/search/domain/browse.py", "source_sha256": "78a1f1d3217e3d6b83573a1d311222cd9d1f66d735d10dc8c96bcee5bda92fa1", "scope": "Empty-query browse routing, filter callback arguments, ordering and precomputed index ownership with ordinary built-in containers; reviewed equivalent survivors are not killed.", "equivalent": {} diff --git a/quality/mutation-reviews/mutation-equivalent-search-candidates.json b/quality/mutation-reviews/mutation-equivalent-search-candidates.json index e1aef7f07bd2a26454e5e55e20025fb17960db76..3f49de647579be4cf7898b9bf343123a80e56ba1 100644 --- a/quality/mutation-reviews/mutation-equivalent-search-candidates.json +++ b/quality/mutation-reviews/mutation-equivalent-search-candidates.json @@ -1,14 +1,14 @@ { "tool": "mutmut 3.8.1", - "source": "backend/search_candidates.py", - "source_sha256": "c311bd8a5b0c0897507c99fe8a72913d05e2d54cfaeec537c29a0eceadfa16f4", + "source": "backend/search/domain/candidates.py", + "source_sha256": "7b362b32e583cf9052eb052ebc154e109d4c26cc51651c2479a478bf47fbcca5", "scope": "Candidate selection with ordinary built-in values and mappings; the application boundary separately tests dynamic state rebinding. An equivalent survivor is not counted as killed.", "equivalent": { - "backend.search_candidates.x_wildcard_literal_candidates__mutmut_12": { + "backend.search.domain.candidates.x_wildcard_literal_candidates__mutmut_12": { "sha256": "fc1187c6b6e80d67363071bf2482cce6072e6872ecd76a0954430c5cc790cf5f", "rationale": "Allowed characters in the regex are ASCII letters and digits or CJK U+3400 and above, never U+007F. Changing > 127 to >= 127 selects exactly the same chunks for built-in strings." }, - "backend.search_candidates.x_wildcard_literal_candidates__mutmut_13": { + "backend.search.domain.candidates.x_wildcard_literal_candidates__mutmut_13": { "sha256": "422a5ba930c851627686dcb7308eaadf3aadb1e3fd7679d31ecfcd39ae360752", "rationale": "Allowed characters in the regex are ASCII letters and digits or CJK U+3400 and above, never U+0080. Changing > 127 to > 128 selects exactly the same chunks for built-in strings." } diff --git a/quality/mutation-reviews/mutation-equivalent-search-execution.json b/quality/mutation-reviews/mutation-equivalent-search-execution.json index 83f5cb8686ed7c3d4894cd43fc54e0fef064501f..864e85fb32117948a3fbb653aa0616dc217a331e 100644 --- a/quality/mutation-reviews/mutation-equivalent-search-execution.json +++ b/quality/mutation-reviews/mutation-equivalent-search-execution.json @@ -1,6 +1,6 @@ { "tool": "mutmut 3.8.1", - "source": "backend/search_execution.py", - "source_sha256": "e30bc01eba1cbf8b13c9cd7ce6165c9fe5165ea6523d93104ade88d5fcc80eec", + "source": "backend/search/infrastructure/executor.py", + "source_sha256": "282ccc3aeb661e977e0c029ca2060412d8af8ffb3586048ef298a14550fa4442", "equivalent": {} } diff --git a/quality/mutation-reviews/mutation-equivalent-search-filters.json b/quality/mutation-reviews/mutation-equivalent-search-filters.json index a40cb71d16a7feace96a3517fde2b74bae242a6a..c83842d2e7b18e5adf92cd6bdc1f4d43e3118e2f 100644 --- a/quality/mutation-reviews/mutation-equivalent-search-filters.json +++ b/quality/mutation-reviews/mutation-equivalent-search-filters.json @@ -1,106 +1,106 @@ { "tool": "mutmut 3.8.1", - "source": "backend/search_filters.py", + "source": "backend/search/domain/filters.py", "source_sha256": "a036da20116e665768ef5046bf2cb9395c647466683dbd27b0317a8ca33a61d1", "scope": "Draft only. Reviews describe runtime return values and exceptions for ordinary builtin strings, lists, dicts, numeric values, and corpus indexes produced by backend/app.py. They do not claim equivalence for arbitrary user-defined overrides or reflection of function defaults.", "equivalent": { - "backend.search_filters.x_apply_filters__mutmut_1": { + "backend.search.domain.filters.x_apply_filters__mutmut_1": { "sha256": "4c2aa34059c7af7ffc6880c906e10506a9cccdfc1f037803ae1bb83789ef8877", "rationale": "For actual calls, the mode is only compared with 'exact'; both default 'prefix' and 'XXprefixXX' take exactly the same non-exact path. Explicitly passed modes are unchanged. The inspectable default value differs." }, - "backend.search_filters.x_apply_filters__mutmut_107": { + "backend.search.domain.filters.x_apply_filters__mutmut_107": { "sha256": "8b00c1c776428aaf362c1918989ed71de27e3a7762a99af79f6442fd904ff9dd", "rationale": "For builtin str.rfind, None as the start index and 0 have identical slice-bound semantics, including when end is nonpositive." }, - "backend.search_filters.x_apply_filters__mutmut_114": { + "backend.search.domain.filters.x_apply_filters__mutmut_114": { "sha256": "d9180681d26b87c3badc6590ac5fe8d00768ed8c939305e5b33b16bd38888ff2", "rationale": "The only additional slash reachable at start index 0 is a slash at position 0. The unchanged loop condition tests end > 0, so neither version examines that ancestor; both terminate without a match at that point." }, - "backend.search_filters.x_apply_filters__mutmut_124": { + "backend.search.domain.filters.x_apply_filters__mutmut_124": { "sha256": "d53b2aab76576baab810f22d5c0b9bab2cd81925e1aaa26940f99b9324794183", "rationale": "For builtin int/float including bool, zero and negative zero are falsy and cannot reach the comparison; nonzero non-NaN values compare identically under > 0 and >= 0; NaN makes both comparisons false." }, - "backend.search_filters.x_apply_filters__mutmut_2": { + "backend.search.domain.filters.x_apply_filters__mutmut_2": { "sha256": "e9d53b98b2077b77bd46a30c3c8fbbadfec2c80764e8dbc0e3059a4dc208831c", "rationale": "For actual calls, the mode is only compared with 'exact'; both default 'prefix' and 'PREFIX' take exactly the same non-exact path. Explicitly passed modes are unchanged. The inspectable default value differs." }, - "backend.search_filters.x_apply_filters__mutmut_23": { + "backend.search.domain.filters.x_apply_filters__mutmut_23": { "sha256": "510fa82c3c7991af56761b9d96a5462dccf7ff0af5787df95994353c40ec8e6c", "rationale": "When root prefix disables filtering, both None and the empty string are falsy at every later read of folder_set; neither is returned." }, - "backend.search_filters.x_apply_filters__mutmut_36": { + "backend.search.domain.filters.x_apply_filters__mutmut_36": { "sha256": "a3c10c8689ff835e71e121a7c00b8b3751f20525a3cc50a378129638604c56de", "rationale": "With a single folder and mode 'exact', this mutant computes an unused prefix; with mode 'XXexactXX', it uses the generic ancestor scan rather than the prefix fast path. For builtin strings and nonempty normalized root f, startswith(f + '/') is true exactly when f occurs as a positive-length slash-delimited ancestor. All other modes use the same path. This differs in computation, not filter results." }, - "backend.search_filters.x_apply_filters__mutmut_37": { + "backend.search.domain.filters.x_apply_filters__mutmut_37": { "sha256": "ac43d130029c7f7e9ad237fcc0a7a00bb1269da5d5c3d5ac1c4739611d6354a6", "rationale": "With a single folder and mode 'exact', this mutant computes an unused prefix; with mode 'EXACT', it uses the generic ancestor scan rather than the prefix fast path. For builtin strings and nonempty normalized root f, startswith(f + '/') is true exactly when f occurs as a positive-length slash-delimited ancestor. All other modes use the same path. This differs in computation, not filter results." }, - "backend.search_filters.x_apply_filters__mutmut_57": { + "backend.search.domain.filters.x_apply_filters__mutmut_57": { "sha256": "82ac41e4b34ababcae0bf57c1795a7d6d9fa5989080f256fe304430a6cbb53fd", "rationale": "The initial rec_path value is never read: if folder_set is truthy it is overwritten before use, and otherwise no subsequent operation reads it." }, - "backend.search_filters.x_apply_filters__mutmut_58": { + "backend.search.domain.filters.x_apply_filters__mutmut_58": { "sha256": "ac787f39a1086e9aa6f7035b1a7d741f37e573e746c541b7019cc5df210250c3", "rationale": "The initial rec_path value is never read: if folder_set is truthy it is overwritten before use, and otherwise no subsequent operation reads it." }, - "backend.search_filters.x_apply_filters__mutmut_62": { + "backend.search.domain.filters.x_apply_filters__mutmut_62": { "sha256": "44c312fd4a53a42517986c393c53de1f2329b7e4e7720ab9e4f41d7d880b2c7d", "rationale": "typing.cast ignores the first argument and returns the same stored path." }, - "backend.search_filters.x_apply_filters__mutmut_73": { + "backend.search.domain.filters.x_apply_filters__mutmut_73": { "sha256": "6e6272f49d12dc94a8e2d194f48e18118c40c246e3e1044fdfe3a1017a033484", "rationale": "typing.cast ignores the first argument and returns the same folder list." }, - "backend.search_filters.x_apply_filters__mutmut_79": { + "backend.search.domain.filters.x_apply_filters__mutmut_79": { "sha256": "23b3a0cd6720edcad1855cd5f95944462ac459c29c639f65802c78f1356b75e6", "rationale": "For an absent Folder key, either [] or None is followed by 'or []', yielding an empty list. For a present key the value is unchanged." }, - "backend.search_filters.x_apply_filters__mutmut_81": { + "backend.search.domain.filters.x_apply_filters__mutmut_81": { "sha256": "8b503c943e61c3083ad14decc713acd3e776307e775839d1e5986849568caf66", "rationale": "dict.get without a default returns None. For an absent Folder key, None or [] both become [] in the following 'or []'; present keys are unchanged." }, - "backend.search_filters.x_apply_filters__mutmut_99": { + "backend.search.domain.filters.x_apply_filters__mutmut_99": { "sha256": "2b741b44d1234c29b697a46a2ee10ee6a56e82fabfb4d1532e93b5d3f816e426", "rationale": "An end index of zero can only add a check for rec_path[:0] == ''. Empty root has already cleared every non-exact folder_set, so this cannot match; rfind('/', 0, 0) then returns -1 and the loop terminates. The exact mode never enters the loop." }, - "backend.search_filters.x_apply_mixed_folder_filters__mutmut_19": { + "backend.search.domain.filters.x_apply_mixed_folder_filters__mutmut_19": { "sha256": "2b03f895e05e01e8741522c8987479e4575a5293709b17d3ff7c46d361b40385", "rationale": "typing.cast ignores its first argument and returns the same folder list; unchanged from the earlier reviewed cast mutant." }, - "backend.search_filters.x_apply_mixed_folder_filters__mutmut_25": { + "backend.search.domain.filters.x_apply_mixed_folder_filters__mutmut_25": { "sha256": "a6612425bf50fc6dd258094633d14d6329ae0d27165979a1841d1cbb364ba4b9", "rationale": "For an absent Folder key, [] and None are both replaced with [] by the following or; present keys are unchanged." }, - "backend.search_filters.x_apply_mixed_folder_filters__mutmut_27": { + "backend.search.domain.filters.x_apply_mixed_folder_filters__mutmut_27": { "sha256": "73349ff5b2268824929b7ac54e8a524c82095f853d2c59eee8bfceeead8bd994", "rationale": "dict.get without a default returns None and the following or [] gives the same result as the original default for an absent key." }, - "backend.search_filters.x_apply_mixed_folder_filters__mutmut_42": { + "backend.search.domain.filters.x_apply_mixed_folder_filters__mutmut_42": { "sha256": "cac6a5a6c12fdf294c43feb7cee618503c7a726ec5c48aea9e10e9ef3f4a2d31", "rationale": "The initial matched value is only used as a truth test; False and None are both falsy and a matching prefix overwrites either with True." }, - "backend.search_filters.x_apply_mixed_folder_filters__mutmut_44": { + "backend.search.domain.filters.x_apply_mixed_folder_filters__mutmut_44": { "sha256": "6690544a8ec9aba5693469cfe2ea907024a8150f63d49cef6ed0b5efc97cb037", "rationale": "The initial prefix is unread if there are no folder components; otherwise the first iteration unconditionally overwrites it before any read." }, - "backend.search_filters.x_apply_mixed_folder_filters__mutmut_45": { + "backend.search.domain.filters.x_apply_mixed_folder_filters__mutmut_45": { "sha256": "ec3d0df4930e48f9e5cf7a93d79fe5639a029abc7ebb834129c074acf6f012e4", "rationale": "The initial prefix is unread if there are no folder components; otherwise the first iteration unconditionally overwrites it before any read." }, - "backend.search_filters.x_mixed_folder_index_candidates__mutmut_39": { + "backend.search.domain.filters.x_mixed_folder_index_candidates__mutmut_39": { "sha256": "f063c352d59397861497739d39ae104cbbcddd029db071fa64a03a327b9ff925", "rationale": "Scope size and estimated posting count are nonnegative integers. Within the uncapped interval, integer estimated > scope_size/2 agrees with estimated > floor(scope_size/2), including odd sizes; min/max clamps at integer 64 and 32768 preserve that decision. The float itself is not returned." }, - "backend.search_filters.x_score_record__mutmut_17": { + "backend.search.domain.filters.x_score_record__mutmut_17": { "sha256": "706abf7d0c920f9661b44aefcb92ef0818d0b6e2bb086f323fd8514ea1f2b1e0", "rationale": "typing.cast ignores the first argument and returns the same record value; str and None do not change evaluation of record.get." }, - "backend.search_filters.x_score_record__mutmut_29": { + "backend.search.domain.filters.x_score_record__mutmut_29": { "sha256": "065264ef2c13b0fe006b1ded139ff579c9615a676b8c9b2df88f8c2de1b58919", "rationale": "typing.cast ignores the first argument and returns the same record value; str and None do not change evaluation of record.get." }, - "backend.search_filters.x_score_record__mutmut_5": { + "backend.search.domain.filters.x_score_record__mutmut_5": { "sha256": "3133a98716a7f85327def82801970b2ea831069e3816e28975b71179e31acb0f", "rationale": "typing.cast ignores the first argument and returns the same record value; str and None do not change evaluation of record.get." } diff --git a/quality/mutation-reviews/mutation-equivalent-search-indexes.json b/quality/mutation-reviews/mutation-equivalent-search-indexes.json index 0617a1c1ed0377be243b3e22af733cbc1dc52c9c..b82020ac71b8a6a1b694ca53d2d63964d66142e0 100644 --- a/quality/mutation-reviews/mutation-equivalent-search-indexes.json +++ b/quality/mutation-reviews/mutation-equivalent-search-indexes.json @@ -1,41 +1,41 @@ { "tool": "mutmut 3.8.1", - "source": "backend/search_indexes.py", + "source": "backend/search/corpus/infrastructure/indexes.py", "source_sha256": "95d1c3fd9e41c0bb1cc875f349c611033fea50eb848b5b4ae2fb39bdc2cdeba5", "equivalent": { - "backend.search_indexes.x__bounded_slice__mutmut_4": { + "backend.search.corpus.infrastructure.indexes.x__bounded_slice__mutmut_4": { "sha256": "b32f7c7ee2394f3fa9e3b795f5d1977f40300c87864de05530be3b6ac63e91e1", "rationale": "For integer offset and length, end=offset+length; therefore length<0 if and only if end= 1. With ordinary Python strings, at start == len(text) the additional loop iteration finds no LF and produces a zero-length segment, cannot match, then exits. The return value remains False; tracing, subclass overrides and performance are outside this equivalence review." }, - "backend.search_matching.x_compile_exact_matcher__mutmut_287": { + "backend.search.domain.matching.x_compile_exact_matcher__mutmut_287": { "sha256": "5890be131c06e7ffa2c43b78584ef7724e9470c698aa1aee4ce0ca189ea88f08", "rationale": "When wildcard is false the changed conditional value is ORed with 1 immediately afterwards; 0 | 1 and 1 | 1 both equal 1. When wildcard is true the changed branch is not evaluated." }, - "backend.search_matching.x_is_fuzzy_match__mutmut_9": { + "backend.search.domain.matching.x_is_fuzzy_match__mutmut_9": { "sha256": "3853f2390cda6fbcca1e514be9e41ee2cd83759579698d7597bb44fb124c30d1", "rationale": "For ordinary strings, using the looser precheck cannot change the final result: edit_distance still enforces the actual token budget. Call counts and performance are outside this equivalence review." }, - "backend.search_matching.x_is_fuzzy_match__mutmut_15": { + "backend.search.domain.matching.x_is_fuzzy_match__mutmut_15": { "sha256": "6a135762b22e09c116fbe1587daa7439d9c25419149cdecd3e3f30017812a50a", "rationale": "The default distance bound is 2, at least as large as every token budget; the final comparison still enforces the actual budget. For ordinary strings the Boolean result is unchanged; work performed is outside this equivalence review." } diff --git a/quality/mutation-reviews/mutation-equivalent-search-words.json b/quality/mutation-reviews/mutation-equivalent-search-words.json index a76890912fa45955566585d8316465e2b09aa0df..4aa28c29e1eba61364936f3ba585273763c1aa56 100644 --- a/quality/mutation-reviews/mutation-equivalent-search-words.json +++ b/quality/mutation-reviews/mutation-equivalent-search-words.json @@ -1,37 +1,37 @@ { "tool": "mutmut 3.8.1", - "source": "backend/search_words.py", + "source": "backend/search/corpus/domain/words.py", "source_sha256": "77f923765a7726bf3f970d53a00f0d5d91c8dbe27a4ab5278067c07cc19edf40", "equivalent": { - "backend.search_words.x_records_digest__mutmut_25": { + "backend.search.corpus.domain.words.x_records_digest__mutmut_25": { "sha256": "48e79d67d85f6988fdd5b40b1375df433f5539bce6a2b9cde1dc25403b1f8f59", "rationale": "typing.cast returns its input unchanged at runtime" }, - "backend.search_words.x_records_digest__mutmut_30": { + "backend.search.corpus.domain.words.x_records_digest__mutmut_30": { "sha256": "1ad9811d310c0b66022d50a505efc1519c8acd5528ee73a4261664ab7aecddd7", "rationale": "UTF-8 codec spelling is case-insensitive" }, - "backend.search_words.x_tokenize__mutmut_29": { + "backend.search.corpus.domain.words.x_tokenize__mutmut_29": { "sha256": "a16df75911e2fcc33e7263423ea42a2c8b166a87d1cfe99e4972efa8334d6770", "rationale": "Unicode escape hex digits are case-insensitive" }, - "backend.search_words.x_matches_file_token__mutmut_3": { + "backend.search.corpus.domain.words.x_matches_file_token__mutmut_3": { "sha256": "cb1cd8969cc247ced7855d5f69d4de0b6b99cd7acedb49e8eef868b55c65f3c4", "rationale": "typing.cast returns its input unchanged at runtime" }, - "backend.search_words.x_matches_file_token__mutmut_21": { + "backend.search.corpus.domain.words.x_matches_file_token__mutmut_21": { "sha256": "6f13349ae260f8ab98aa6580ea18b44eb615f3d06317f2998e9f56eccb947841", "rationale": "typing.cast returns its input unchanged at runtime" }, - "backend.search_words.x_matches_file_query__mutmut_5": { + "backend.search.corpus.domain.words.x_matches_file_query__mutmut_5": { "sha256": "281d996a9dbcb5052d31277f4c8d99fcf00f384f06dbdf39545136bad27094f0", "rationale": "typing.cast returns its input unchanged at runtime" }, - "backend.search_words.x_build_word_index__mutmut_3": { + "backend.search.corpus.domain.words.x_build_word_index__mutmut_3": { "sha256": "93ae2f68fce2e51a95a402b35e53361c5599677040ffa29c9f9468954c408b63", "rationale": "typing.cast returns its input unchanged at runtime" }, - "backend.search_words.x_build_word_index__mutmut_16": { + "backend.search.corpus.domain.words.x_build_word_index__mutmut_16": { "sha256": "229ff52c4b95cf7d6ad34d125f324cfc47a6e42741e1b4f91e9178826fc5b350", "rationale": "typing.cast returns its input unchanged at runtime" } diff --git a/quality/mutation-reviews/mutation-equivalent-upstream-http.json b/quality/mutation-reviews/mutation-equivalent-upstream-http.json index 842532f3afe144a8af6fc15b5331e468ff977345..61fe213bbe6836998311fe7b1817e6ae693523e0 100644 --- a/quality/mutation-reviews/mutation-equivalent-upstream-http.json +++ b/quality/mutation-reviews/mutation-equivalent-upstream-http.json @@ -1,41 +1,41 @@ { "tool": "mutmut 3.8.1", - "source": "backend/upstream_http.py", + "source": "backend/shared/transport/upstream.py", "source_sha256": "73f6bb9dda28ab2822c19e9810c67b1efe053bcd52c0d4af269e2d240a261374", "equivalent": { - "backend.upstream_http.x_validate_voiceofml_redirect_url__mutmut_18": { + "backend.shared.transport.upstream.x_validate_voiceofml_redirect_url__mutmut_18": { "sha256": "6215811bb0cc4935623ffd912e53164650d9f24d318cb99cf21dd85dba43ebfa", "rationale": "The constructed URL is only passed to validate_voiceofml_source_url. urllib.parse normalizes the HTTPS scheme and hostname case; the validator checks those parsed fields and the identical path, and the constructed string is not returned." }, - "backend.upstream_http.x_validate_reader_redirect_url__mutmut_18": { + "backend.shared.transport.upstream.x_validate_reader_redirect_url__mutmut_18": { "sha256": "2274c04f92f2c1360c20edc3180aa0ce03ad7809460adf92e69417b68cbd6bde", "rationale": "The constructed URL is only passed to validate_reader_source_url. urllib.parse normalizes the HTTPS scheme and hostname case; the validator checks those parsed fields and the identical path, and the constructed string is not returned." }, - "backend.upstream_http.x__request__mutmut_2": { + "backend.shared.transport.upstream.x__request__mutmut_2": { "sha256": "689b1d9ee7f188d1880514e7276fc09287e0d9f8856d7d893ebba019f68faeaf", "rationale": "typing.cast returns its second argument unchanged at runtime; the GenericRequest type expression and None do not change the selected session.request callable." }, - "backend.upstream_http.x__request__mutmut_21": { + "backend.shared.transport.upstream.x__request__mutmut_21": { "sha256": "1dc4224d572376ff4096f8ac21f467cb2fedb1fe67109d8c7b78804d3804c20b", "rationale": "typing.cast returns its second argument unchanged at runtime; the MethodRequest type expression and None do not change the selected method-specific callable." }, - "backend.upstream_http.x_open_download_response__mutmut_2": { + "backend.shared.transport.upstream.x_open_download_response__mutmut_2": { "sha256": "0972a8f632213cf720a1887a44fe6761f937d79b09ea15407b7760a30c832c4c", "rationale": "The default method is immediately normalized with method.upper() before validation, cache lookup or transport use; GET and get therefore have identical behavior." }, - "backend.upstream_http.x_open_download_response__mutmut_40": { + "backend.shared.transport.upstream.x_open_download_response__mutmut_40": { "sha256": "debcf49ae00756e2965c540a81cb477b00d5854e8f6dbcd3f8e8d78be0f2acd4", "rationale": "A second outer iteration has from_cache=False because cached is reset and only attempt zero reads the cache. Thereafter a transport error is raised, a response is returned, validation is raised, or redirect exhaustion is raised; no path reaches a third iteration." }, - "backend.upstream_http.x_open_download_response__mutmut_57": { + "backend.shared.transport.upstream.x_open_download_response__mutmut_57": { "sha256": "6d808f032189eb61e6f63ef1b22291c893c8ac701ff17582aa67436ec53021a9", "rationale": "Before the first redirect current_url equals cached whenever cached is not None, and equals validated_url otherwise; the only use of walked also requires current_url != cached. After any redirect walked is unconditionally set to True. Initial None therefore cannot change caching or return behavior." }, - "backend.upstream_http.x_open_download_response__mutmut_138": { + "backend.shared.transport.upstream.x_open_download_response__mutmut_138": { "sha256": "09403a89904a0935c902f52ec7f21f95a57a1150707a5fd1e3fe42dd661b9824", "rationale": "The final RuntimeError is unreachable: a retry can occur only after attempt zero used a cached target; attempt one resets cached to None and every success, failure, or redirect exhaustion returns or raises within the inner loop. Changing this defensive error message has no runtime effect." }, - "backend.upstream_http.x_open_download_response__mutmut_139": { + "backend.shared.transport.upstream.x_open_download_response__mutmut_139": { "sha256": "cf4fd6d8f8ef07dff789f54f8f4c3bb1cfd1be3221a8d77eced4e60856a8e8b9", "rationale": "The final RuntimeError is unreachable: a retry can occur only after attempt zero used a cached target; attempt one resets cached to None and every success, failure, or redirect exhaustion returns or raises within the inner loop. Changing this defensive error message has no runtime effect." } diff --git a/scripts/backend_paths.py b/scripts/backend_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..ed9bafe150df3f5c50b7dd66eb3ea0b27283591c --- /dev/null +++ b/scripts/backend_paths.py @@ -0,0 +1,87 @@ +"""Bounded path-only migration proof for canonical backend implementations. + +Frozen historical anchors remain unchanged. Reversing the exact recorded import +lines reconstructs their source bytes without shifting any coverage coordinate. +""" +import hashlib +import json +from pathlib import Path + +MAP_FILE = 'quality/backend-path-migration.json' +MAP_SHA = 'de3275d169af9795a92185609797178a282802309f43c1f2628e65b75f0b6e76' + + +def migration(root: Path) -> dict: + raw = (root / MAP_FILE).read_bytes() + if hashlib.sha256(raw).hexdigest() != MAP_SHA: + raise ValueError('backend path migration requires exact reviewed mapping') + return json.loads(raw) + + +def has_migration(root: Path) -> bool: + if (root / MAP_FILE).is_file(): + return True + # Historical fixture trees restore the original implementations. A live + # migrated tree must never fall back to hashing compatibility imports. + if any('sys.modules[__name__] = _implementation' in path.read_text() + for path in (root / 'backend').glob('*.py')): + raise ValueError('backend path migration mapping is missing') + return False + + +def canonical_path(root: Path, name: str) -> Path: + if not has_migration(root): + return root / name + return root / migration(root)['moves'].get(name, name) + + +def reviewed_source(root: Path, name: str) -> bytes: + """Validate the real implementation, then reconstruct pre-move import text.""" + if not has_migration(root): + return (root / name).read_bytes() + manifest = migration(root) + entry = manifest['sources'].get(name) + if entry is None: + return (root / name).read_bytes() + data = (root / entry['target']).read_bytes() + if hashlib.sha256(data).hexdigest() != entry['after_sha256']: + raise ValueError('backend path migration requires exact canonical source: ' + entry['target']) + lines = data.decode().splitlines(keepends=True) + for number, before, after in entry['imports']: + if lines[number - 1] != after or not before.lstrip().startswith('from ') or not after.lstrip().startswith('from '): + raise ValueError('backend path migration permits only reviewed import lines') + lines[number - 1] = before + if 'logger_identity' in entry: + expected = [12, 'logger = logging.getLogger(__name__)\n', + 'logger = logging.getLogger("backend.search_execution")\n'] + if name != 'backend/search_execution.py' or entry['logger_identity'] != expected or lines[11] != expected[2]: + raise ValueError('backend path migration requires preserved executor logger identity') + lines[11] = expected[1] + restored = ''.join(lines).encode() + if hashlib.sha256(restored).hexdigest() != entry['before_sha256']: + raise ValueError('backend path migration failed source reconstruction: ' + name) + return restored + + +def validate_migration(root: Path) -> None: + manifest = migration(root) + for name, entry in manifest['sources'].items(): + reviewed_source(root, name) + if 'compatibility_sha256' in entry: + if hashlib.sha256((root / name).read_bytes()).hexdigest() != entry['compatibility_sha256']: + raise ValueError('backend path migration requires exact compatibility import: ' + name) + + +def migrate_paths(root: Path, baseline: dict) -> dict: + """Rename debt entries only; every covered/missing line, arc and count survives.""" + if not has_migration(root): + return baseline + validate_migration(root) + moves = migration(root)['moves'] + result = {} + for name, entry in baseline.items(): + target = moves.get(name, name) + if target in result: + raise ValueError('duplicate backend coverage destination: ' + target) + result[target] = dict(entry) + return result diff --git a/scripts/build/check_reader_release.mjs b/scripts/build/check_reader_release.mjs index 2c2f8159c728253f65234121d379167045b4f9b2..e5aa0a4f2b56ba042c7c24214f8dd23238c64edb 100644 --- a/scripts/build/check_reader_release.mjs +++ b/scripts/build/check_reader_release.mjs @@ -245,20 +245,20 @@ function crossCheck(githubRoot, hfRoot) { "reader/search/reader-pdf-book-validate.mjs", "reader/search/workers/reader-pdf-book-search-worker.mjs", "reader/search/reader-pdf-book-search.mjs", - "search/search-session.js", - "search/download-controller.js", + "search/execution/application/session.js", + "search/downloads/application/controller.js", "search/execution/domain/policy.js", "search/execution/application/controller.js", "search/downloads/application/batch.js", "search/downloads/presentation/queue.js", - "search/size-format.js", - "search/record-path.js", - "search/highlight.js", - "search/response-cache.js", - "search/file-types.js", - "search/response-validation.js", - "search/result-identity.js", - "search/folder-selection.js", + "search/results/presentation/size-format.js", + "search/catalog/domain/record-path.js", + "search/results/presentation/highlight.js", + "search/requests/infrastructure/response-cache.js", + "search/catalog/domain/file-types.js", + "search/requests/domain/response-validation.js", + "search/results/domain/result-identity.js", + "search/sidebar/domain/folder-selection.js", "search/input/domain/ownership.js", "search/input/application/controller.js", "search/results/domain/paging-policy.js", @@ -280,7 +280,7 @@ function crossCheck(githubRoot, hfRoot) { "search/sidebar/infrastructure/scroll.js", "search/sidebar/presentation/directory.js", "search/sidebar/application/directory.js", - "search/reader-navigation.js", + "search/reader-host/application/navigation.js", "search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js", "search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js", "search/positions/application/restoration.js", "search/results/presentation/row.js", "search/results/application/interactions.js", diff --git a/scripts/build/compose_app.mjs b/scripts/build/compose_app.mjs index c590beeb84965d7ddc0fa57446cfc882d2c0043b..18826d9c16f017a5eeca37874b9bb84c48413015 100644 --- a/scripts/build/compose_app.mjs +++ b/scripts/build/compose_app.mjs @@ -5,7 +5,7 @@ import { pathToFileURL } from "node:url"; // One ordered dependency list owns the production app and its shell scripts. // Keep classic-script globals for the host; each dependency owns its own scope. export const APP_DEPENDENCIES = Object.freeze([ - "reader-resources.js", "reader/core/reader-contract.js", "search/reader-navigation.js", + "reader-resources.js", "reader/core/reader-contract.js", "search/reader-host/application/navigation.js", "search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js", "search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js", "search/positions/application/restoration.js", "search/results/presentation/row.js", "search/results/application/interactions.js", @@ -20,14 +20,14 @@ export const APP_DEPENDENCIES = Object.freeze([ "search/ambient/application/quotation.js", "search/results/snapshots/domain/copy-budget.js", "search/results/snapshots/application/store.js", "search/execution/domain/policy.js", "search/execution/application/controller.js", - "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", - "search/highlight.js", "search/response-cache.js", "search/file-types.js", "search/response-validation.js", "search/result-identity.js", + "search/execution/application/session.js", "search/downloads/application/controller.js", "search/downloads/application/batch.js", "search/downloads/presentation/queue.js", "search/results/presentation/size-format.js", "search/catalog/domain/record-path.js", + "search/results/presentation/highlight.js", "search/requests/infrastructure/response-cache.js", "search/catalog/domain/file-types.js", "search/requests/domain/response-validation.js", "search/results/domain/result-identity.js", "search/input/domain/ownership.js", "search/input/application/controller.js", "search/requests/infrastructure/shared-transport.js", "search/requests/application/prefetch-controller.js", "search/requests/application/response-store.js", "search/catalog/domain/sidebar-payload.js", "search/catalog/application/client.js", "search/results/window/application/page-loader.js", "search/results/window/presentation/status.js", "search/results/domain/paging-policy.js", "search/results/application/paging-controller.js", "search/results/presentation/paging-status.js", - "search/folder-selection.js", "search/domain/height-index.js", "search/domain/stable-stringify.js", "search/domain/search-view-key.js", "search/domain/search-recovery.js", "search/domain/search-window-page.js", "search/presentation/sidebar-render.js", "search/sidebar/presentation/filter-list.js", "search/sidebar/presentation/folder-tree.js", "search/sidebar/application/filters.js", "search/sidebar/infrastructure/scroll.js", "search/sidebar/presentation/directory.js", "search/sidebar/application/directory.js" + "search/sidebar/domain/folder-selection.js", "search/domain/height-index.js", "search/domain/stable-stringify.js", "search/domain/search-view-key.js", "search/domain/search-recovery.js", "search/domain/search-window-page.js", "search/presentation/sidebar-render.js", "search/sidebar/presentation/filter-list.js", "search/sidebar/presentation/folder-tree.js", "search/sidebar/application/filters.js", "search/sidebar/infrastructure/scroll.js", "search/sidebar/presentation/directory.js", "search/sidebar/application/directory.js" ]); export function stripBundledScripts(html) { diff --git a/scripts/check_backend_coverage.py b/scripts/check_backend_coverage.py index 638af72398070560baa371d498174739f468dae8..976267b01676b42d0d74913ed656bfe2115d3006 100644 --- a/scripts/check_backend_coverage.py +++ b/scripts/check_backend_coverage.py @@ -16,6 +16,7 @@ import sys if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from scripts.check_transport_coverage import transport_baseline, transport_layout +from scripts.backend_paths import canonical_path ROOT = Path(__file__).resolve().parents[1] BASELINE_FILE = "quality/baselines/backend-coverage-debt.json" @@ -1712,31 +1713,31 @@ def migrate_ci_baseline_to_lifespan_parent(root: Path, previous: dict) -> dict: source("search-candidates-new-app"), source("search-candidates-new-module")), (migrate_search_bootstrap_app_baseline, source("search-candidates-new-app"), source("search-bootstrap-new-app"), source("search-bootstrap-new-module")), - (migrate_native_postings_baseline, source("native-postings-old-index"), root / "backend/search_indexes.py"), + (migrate_native_postings_baseline, source("native-postings-old-index"), canonical_path(root, "backend/search_indexes.py")), (migrate_star_browse_app_baseline, source("star-browse-old-app"), source("pdf-limit-old-app")), (migrate_pdf_limit_app_baseline, source("pdf-limit-old-app"), source("reader-archive-old-app")), (migrate_reader_archive_app_baseline, source("reader-archive-old-app"), source("reader-archive-new-app"), source("reader-archive-new-module")), (migrate_backend_typing_app_baseline, source("reader-archive-new-app"), source("backend-typing-new-app")), (migrate_folder_contents_app_baseline, source("backend-typing-new-app"), - source("range-cache-old-app"), root / "backend/folder_contents.py"), + source("range-cache-old-app"), canonical_path(root, "backend/folder_contents.py")), (migrate_reader_range_app_baseline, source("range-cache-old-app"), source("term-candidates-old-app"), source("proxy-safety-old-range")), (migrate_search_term_app_baseline, source("term-candidates-old-app"), source("download-warm-old-app"), source("single-term-old-module")), (migrate_download_warm_app_baseline, source("download-warm-old-app"), - source("single-term-old-app"), root / "backend/download_warm.py"), + source("single-term-old-app"), canonical_path(root, "backend/download_warm.py")), (migrate_single_term_app_baseline, source("single-term-old-app"), source("search-release-old-app"), source("search-release-old-term")), (migrate_search_release_baseline, source("search-release-old-app"), source("search-release-new-app"), source("search-release-old-term"), source("search-release-new-term")), (migrate_search_sigma_baseline, source("search-release-new-app"), source("search-sigma-new-app")), - (migrate_seo_path_baseline, source("seo-path-old-seo"), root / "backend/seo.py", + (migrate_seo_path_baseline, source("seo-path-old-seo"), canonical_path(root, "backend/seo.py"), anchors / "seo-path-old-debt.json"), (migrate_proxy_safety_baseline, source("proxy-safety-old-app"), source("proxy-safety-new-app"), source("proxy-safety-old-streams"), source("proxy-safety-new-streams")), (migrate_search_browse_baseline, source("proxy-safety-new-app"), - source("lifespan-parent-app"), root / "backend/search_browse.py"), + source("lifespan-parent-app"), canonical_path(root, "backend/search_browse.py")), ) for migrate, *sources in steps: previous = migrate(previous, *sources) diff --git a/scripts/check_refactor_coverage.py b/scripts/check_refactor_coverage.py index aa1a27e531329bc4991c88257f4ba20e541b9111..fa09b6e9ca8b7da6d04f465c2ea65ac67588b76e 100644 --- a/scripts/check_refactor_coverage.py +++ b/scripts/check_refactor_coverage.py @@ -9,6 +9,7 @@ import ast import hashlib import json from pathlib import Path +from scripts.backend_paths import reviewed_source MAP_FILE = 'scripts/coverage-anchors/refactor23-map.json' MAP_SHA = '28c0bfc6825799cc1e851c0eefb06949341cc332a63557888781fff49d83a5e1' @@ -44,7 +45,7 @@ def migrate_refactor_baseline(root: Path, previous: dict) -> dict: raise ValueError('refactor coverage requires exact reviewed source parent') symbols = {} for name, digest in manifest['sources'].items(): - data = (root / name).read_bytes() + data = reviewed_source(root, name) if hashlib.sha256(data).hexdigest() != digest: raise ValueError(f'refactor coverage requires exact reviewed source: {name}') symbols[name] = _symbols(data) diff --git a/scripts/check_search_words_mutation.py b/scripts/check_search_words_mutation.py index eb9ecb9be8e710499f4b47a22964a518f31e2f84..b26f9ed95b3928688b09bd93199d1b1de78ec4fc 100644 --- a/scripts/check_search_words_mutation.py +++ b/scripts/check_search_words_mutation.py @@ -15,6 +15,27 @@ import sys import tempfile ROOT = Path(__file__).resolve().parents[1] +# The reviewed source inventory selects real implementations, never compatibility imports. +MODULE_PATHS = { + "search_words": "search/corpus/domain/words", + "search_matching": "search/domain/matching", + "data_formats": "search/corpus/domain/formats", + "search_indexes": "search/corpus/infrastructure/indexes", + "reader_identity": "reader/query/domain/identity", + "cache_core": "shared/cache/core", + "reader_index": "reader/catalog/domain/index", + "upstream_http": "shared/transport/upstream", + "search_execution": "search/infrastructure/executor", + "record_metadata": "search/corpus/domain/records", + "search_filters": "search/domain/filters", + "proxy_streams": "shared/transport/streams", + "folder_tree": "search/corpus/domain/folder_tree", + "search_projection": "search/domain/projection", + "search_candidates": "search/domain/candidates", + "search_bootstrap": "search/application/bootstrap", + "search_browse": "search/domain/browse", + "reader_archive": "reader/archive/domain/validation", +} TOOL_VERSION = "3.8.1" SELECTED_TESTS = [ "test_ascii_cjk_and_punctuation_tokens_with_injected_segmenter", @@ -161,8 +182,7 @@ def main() -> int: parser.add_argument("--module", choices=tuple(SPECS), default="search_words") module = parser.parse_args().module test_name, selected, dependencies = SPECS[module] - module_path = {"search_projection": "search/domain/projection", - "reader_identity": "reader/query/domain/identity"}.get(module, module) + module_path = MODULE_PATHS[module] source = ROOT / "backend" / f"{module_path}.py" test = ROOT / "tests" / test_name equivalent = ROOT / "quality/mutation-reviews" / f"mutation-equivalent-{module.replace('_', '-')}.json" @@ -176,18 +196,21 @@ def main() -> int: temp = Path(directory) (temp / "backend").mkdir() (temp / "tests").mkdir() - shutil.copyfile(ROOT / "backend/__init__.py", temp / "backend/__init__.py") - target_source = temp / "backend" / f"{module_path}.py" - target_source.parent.mkdir(parents=True, exist_ok=True) - packages = {"search_projection": ("search", "search/domain"), - "reader_identity": ("reader", "reader/query", "reader/query/domain")}.get(module, ()) - for package in packages: - shutil.copyfile(ROOT / "backend" / package / "__init__.py", temp / "backend" / package / "__init__.py") - if module == "reader_identity": - shutil.copyfile(ROOT / "backend/reader_identity.py", temp / "backend/reader_identity.py") - shutil.copyfile(source, target_source) + def copy_module(name: str) -> None: + relative = Path('backend') / (MODULE_PATHS[name] + '.py') + destination = temp / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, destination) + for parent in relative.parents: + if parent == Path('.'): + break + shutil.copyfile(ROOT / parent / '__init__.py', temp / parent / '__init__.py') + compatibility = Path('backend') / (name + '.py') + if (ROOT / compatibility).is_file(): + shutil.copyfile(ROOT / compatibility, temp / compatibility) + copy_module(module) for dependency in dependencies: - shutil.copyfile(ROOT / "backend" / dependency, temp / "backend" / dependency) + copy_module(Path(dependency).stem) target_test = temp / "tests" / test_name target_test.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(test, target_test) diff --git a/scripts/check_transport_coverage.py b/scripts/check_transport_coverage.py index 9cf5a2a81eb35aa9576fd4b70a3006328be59f05..d1193affd98e15cc71c1d298519c5212ad437e27 100644 --- a/scripts/check_transport_coverage.py +++ b/scripts/check_transport_coverage.py @@ -3,6 +3,7 @@ import difflib import hashlib import json from pathlib import Path +from scripts.backend_paths import reviewed_source, migrate_paths APP_SHA = '769155429400702a51524f3d2cf2d6dee19b26f67ea08a1f9db22aec70fa61ef' STREAMS_SHA = '02c6df15f5058d322042f99b1e8cd454380b5059c7ac9815cddf49bbf3296d6a' @@ -21,7 +22,7 @@ def transport_baseline(root: Path, baseline: dict) -> dict: from scripts.check_refactor_coverage import refactor_layout, migrate_refactor_baseline if refactor_layout(root): parent = root / 'scripts/coverage-anchors/refactor-parent-app.py.snapshot' - return migrate_refactor_baseline(root, _transport_baseline(root, baseline, parent)) + return migrate_paths(root, migrate_refactor_baseline(root, _transport_baseline(root, baseline, parent))) return _transport_baseline(root, baseline, root / 'backend/app.py') @@ -41,8 +42,8 @@ def _transport_baseline(root: Path, baseline: dict, app_source: Path) -> dict: 'scripts/coverage-anchors/lifespan-parent-backend-coverage-debt.json': LIFESPAN_PARENT_DEBT_SHA, } for name, digest in expected.items(): - source = app_source if name == 'backend/app.py' else root / name - if hashlib.sha256(source.read_bytes()).hexdigest() != digest: + data = app_source.read_bytes() if name == 'backend/app.py' else reviewed_source(root, name) + if hashlib.sha256(data).hexdigest() != digest: raise ValueError(f'transport coverage requires exact reviewed source: {name}') pinned = json.loads((anchors / 'lifespan-parent-backend-coverage-debt.json').read_text()) # The stored debt stays in its independently pinned historical coordinates. @@ -61,9 +62,9 @@ def _transport_baseline(root: Path, baseline: dict, app_source: Path) -> dict: ('backend/app.py', anchors / 'transport-parent-app.py.snapshot'), ('backend/proxy_streams.py', anchors / 'proxy-safety-new-streams.py.snapshot'), ): - source = app_source if name == 'backend/app.py' else root / name + data = app_source.read_bytes() if name == 'backend/app.py' else reviewed_source(root, name) operations = difflib.SequenceMatcher(None, old.read_text().splitlines(), - source.read_text().splitlines(), autojunk=False).get_opcodes() + data.decode().splitlines(), autojunk=False).get_opcodes() mapping = {i + 1: j + 1 + i - start for op, start, end, j, _ in operations if op == 'equal' for i in range(start, end)} def line(n): @@ -88,7 +89,7 @@ def _transport_baseline(root: Path, baseline: dict, app_source: Path) -> dict: name = 'backend/reader_v3_catalog.py' old = anchors / 'catalog-parent.py.snapshot' operations = difflib.SequenceMatcher(None, old.read_text().splitlines(), - (root / name).read_text().splitlines(), autojunk=False).get_opcodes() + reviewed_source(root, name).decode().splitlines(), autojunk=False).get_opcodes() mapping = {i + 1: j + 1 + i - start for op, start, end, j, _ in operations if op == 'equal' for i in range(start, end)} def translate(n): diff --git a/scripts/search/check_download_controller_coverage.mjs b/scripts/search/check_download_controller_coverage.mjs index 435661ebf2f3c0b4e29452b1194efb8a363ea7e9..cbe46b41dd8598ceb27982400cd2c49e5ed4d57c 100644 --- a/scripts/search/check_download_controller_coverage.mjs +++ b/scripts/search/check_download_controller_coverage.mjs @@ -6,7 +6,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; const minimum = [100, 88.89, 100]; const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/download-controller.js", + "--test-coverage-include=**/static/search/downloads/application/controller.js", ...minimum.map((value, index) => `--test-coverage-${["lines", "branches", "functions"][index]}=${value}`), "tests/search/download/test_download_controller_contract.js" ], {encoding: "utf8"}); @@ -15,7 +15,7 @@ if (result.stderr) process.stderr.write(result.stderr); if (result.error) throw result.error; const text = result.stdout || ""; const rows = text.split(/\r?\n/).flatMap(line => { - const match = /^\s*#\s*download-controller\.js\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|/.exec(line); + const match = /^\s*#\s*controller\.js\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|/.exec(line); return match ? [match.slice(1).map(Number)] : []; }); const required = [ diff --git a/scripts/search/check_reader_navigation_baseline.mjs b/scripts/search/check_reader_navigation_baseline.mjs index 0c4febd18ecda0ce654f241dcc1f03faebc8b519..dcb9d2b2d81f5521f28fd9b3921481ab909e7e9f 100644 --- a/scripts/search/check_reader_navigation_baseline.mjs +++ b/scripts/search/check_reader_navigation_baseline.mjs @@ -6,7 +6,7 @@ import {hasPassingTapContracts} from '../check_tap_contracts.mjs'; const minimum = [31.96, 81.82, 27.27]; const result = spawnSync(process.execPath, [ '--test', '--test-reporter=tap', '--experimental-test-coverage', - '--test-coverage-include=**/static/search/reader-navigation.js', + '--test-coverage-include=**/static/search/reader-host/application/navigation.js', ...minimum.map((value, index) => `--test-coverage-${['lines', 'branches', 'functions'][index]}=${value}`), 'tests/search/reader-navigation/test_reader_navigation_baseline.mjs' ], {encoding: 'utf8'}); @@ -15,7 +15,7 @@ if (result.stderr) process.stderr.write(result.stderr); if (result.error) throw result.error; const text = result.stdout || ''; const rows = text.split(/\r?\n/).flatMap(line => { - const match = /^\s*#\s*reader-navigation\.js\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|/.exec(line); + const match = /^\s*#\s*navigation\.js\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|\s*(\d+(?:\.\d+)?)\s*\|/.exec(line); return match ? [match.slice(1).map(Number)] : []; }); const required = [ diff --git a/scripts/search/check_search_file_types_coverage.mjs b/scripts/search/check_search_file_types_coverage.mjs index b38cc6af93844a6a88c62067fb0e6c2a4d8e001a..2734e94c60c55142fa5e0513ffdbdf8daa35216d 100644 --- a/scripts/search/check_search_file_types_coverage.mjs +++ b/scripts/search/check_search_file_types_coverage.mjs @@ -6,7 +6,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; // also require every named behavioral contract to actually run. const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/file-types.js", + "--test-coverage-include=**/static/search/catalog/domain/file-types.js", "--test-coverage-lines=100", "--test-coverage-branches=100", "--test-coverage-functions=100", "tests/search/baselines/test_search_extension_inventory_baseline.mjs" ], {encoding: "utf8"}); diff --git a/scripts/search/check_search_folder_selection_coverage.mjs b/scripts/search/check_search_folder_selection_coverage.mjs index 302cbf1920ade7c9d3a3feebe76e12ede20e3056..9d88c73480fd81c659105759b00368324ba0a338 100644 --- a/scripts/search/check_search_folder_selection_coverage.mjs +++ b/scripts/search/check_search_folder_selection_coverage.mjs @@ -4,7 +4,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; // Node 26/V8 scope: extracted folder selection module only, excluding the host app. const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/folder-selection.js", + "--test-coverage-include=**/static/search/sidebar/domain/folder-selection.js", "--test-coverage-lines=100", "--test-coverage-branches=100", "--test-coverage-functions=100", "tests/search/baselines/test_search_folder_selection_baseline.mjs" ], {encoding: "utf8"}); diff --git a/scripts/search/check_search_highlight_coverage.mjs b/scripts/search/check_search_highlight_coverage.mjs index 6884b41e65d076d0a4638f79afb4dc0c42ecbe0b..db861e5a2370528410ed99b6af42860d9e9b71cd 100644 --- a/scripts/search/check_search_highlight_coverage.mjs +++ b/scripts/search/check_search_highlight_coverage.mjs @@ -1,13 +1,13 @@ import {spawnSync} from "node:child_process"; import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; -// Node 26/V8 scope: search/highlight.js and its pinned behavior contracts. +// Node 26/V8 scope: search/results/presentation/highlight.js and its pinned behavior contracts. // The unhit branch guards an empty RegExp match, which ordinary escaped terms // cannot produce. Reject an unloaded source or any passing-but-empty report. const minimum = [100, 95.45, 100]; const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/highlight.js", + "--test-coverage-include=**/static/search/results/presentation/highlight.js", ...minimum.map((value, index) => `--test-coverage-${["lines", "branches", "functions"][index]}=${value}`), "tests/search/highlight/test_search_highlight_contract.js" ], {encoding: "utf8"}); diff --git a/scripts/search/check_search_record_path_coverage.mjs b/scripts/search/check_search_record_path_coverage.mjs index 1a9a6053de7f3975c6e663f0c84cc0db31b4e93c..c7ed458664b7926089b2f975d184a368552276b5 100644 --- a/scripts/search/check_search_record_path_coverage.mjs +++ b/scripts/search/check_search_record_path_coverage.mjs @@ -5,7 +5,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; // Require a real source row as well as passing tests and full coverage. const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/record-path.js", + "--test-coverage-include=**/static/search/catalog/domain/record-path.js", "--test-coverage-lines=100", "--test-coverage-branches=100", "--test-coverage-functions=100", "tests/search/record-path/test_search_record_path.js" ], {encoding: "utf8"}); diff --git a/scripts/search/check_search_response_cache_coverage.mjs b/scripts/search/check_search_response_cache_coverage.mjs index 3e7314e8a8c3bf422eee0df7d6335be5d3ae6fb9..795095808a31df5fe87a5714f5c0a229799c8f2c 100644 --- a/scripts/search/check_search_response_cache_coverage.mjs +++ b/scripts/search/check_search_response_cache_coverage.mjs @@ -5,7 +5,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; // A missing source row or a failed test must never pass as empty coverage. const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/response-cache.js", + "--test-coverage-include=**/static/search/requests/infrastructure/response-cache.js", "--test-coverage-lines=100", "--test-coverage-branches=100", "--test-coverage-functions=100", "tests/search/response-cache/test_search_response_cache_contract.js" ], {encoding: "utf8"}); diff --git a/scripts/search/check_search_response_validation_coverage.mjs b/scripts/search/check_search_response_validation_coverage.mjs index 41626e41b137960c03f5eaea356f4359537f1de7..b4b12cff8a1c55f5796134f678e2f0d257899840 100644 --- a/scripts/search/check_search_response_validation_coverage.mjs +++ b/scripts/search/check_search_response_validation_coverage.mjs @@ -4,7 +4,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; // Node 26/V8 scope: extracted response validator only, excluding the host. const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/response-validation.js", + "--test-coverage-include=**/static/search/requests/domain/response-validation.js", "--test-coverage-lines=100", "--test-coverage-branches=100", "--test-coverage-functions=100", "tests/search/baselines/test_search_response_validation_baseline.mjs" ], {encoding: "utf8"}); diff --git a/scripts/search/check_search_result_identity_coverage.mjs b/scripts/search/check_search_result_identity_coverage.mjs index 7df92d41cf79adaa302234977586c03c8972a901..70a6880aa72d634550ba0e2ed9dd3081ccccafe6 100644 --- a/scripts/search/check_search_result_identity_coverage.mjs +++ b/scripts/search/check_search_result_identity_coverage.mjs @@ -4,7 +4,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; // Node 26/V8 scope: extracted identity module only, excluding host and path helper. const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/result-identity.js", + "--test-coverage-include=**/static/search/results/domain/result-identity.js", "--test-coverage-lines=100", "--test-coverage-branches=100", "--test-coverage-functions=100", "tests/search/baselines/test_search_stable_id_baseline.mjs" ], {encoding: "utf8"}); diff --git a/scripts/search/check_search_size_coverage.mjs b/scripts/search/check_search_size_coverage.mjs index a14029d9733a04a30ce3f47541d01ed09f0b766c..f30d673fae9f50fa8d194e2f0c146064cd5e9b36 100644 --- a/scripts/search/check_search_size_coverage.mjs +++ b/scripts/search/check_search_size_coverage.mjs @@ -5,7 +5,7 @@ import {hasPassingTapContracts} from "../check_tap_contracts.mjs"; // vectors; an unloaded file must not be accepted as an empty 100% report. const result = spawnSync(process.execPath, [ "--test", "--test-reporter=tap", "--experimental-test-coverage", - "--test-coverage-include=**/static/search/size-format.js", + "--test-coverage-include=**/static/search/results/presentation/size-format.js", "--test-coverage-lines=100", "--test-coverage-branches=100", "--test-coverage-functions=100", "tests/search/size/test_search_size_format.js", "tests/search/size/test_search_size_render_contract.js" ], {encoding: "utf8"}); diff --git a/static/index.html b/static/index.html index ade8e346638bd0cc22ecbbfd1648e58ca90d92e1..3fd80d1050de426bfe9679183ecf68a007484e79 100644 --- a/static/index.html +++ b/static/index.html @@ -337,7 +337,7 @@ if ("serviceWorker" in navigator) { - + @@ -358,20 +358,20 @@ if ("serviceWorker" in navigator) { - - + + - - - - - - - - + + + + + + + + diff --git a/static/reader-resources.js b/static/reader-resources.js index 5e8817e9129bd854e0881bda44c627140c945a3f..004a067edaecf1c94d5e6e5906cce8ba6d8e894e 100644 --- a/static/reader-resources.js +++ b/static/reader-resources.js @@ -126,7 +126,7 @@ "reader/search/workers/reader-chapter-search-worker.mjs", "reader/search/reader-chapter-search.mjs", "reader/core/reader-contract.js", - "search/reader-navigation.js", + "search/reader-host/application/navigation.js", "search/reader-host/presentation/return-position.js", "search/reader-host/application/host.js", "search/positions/domain/policy.js", "search/positions/infrastructure/indexed-db.js", "search/positions/application/persistence.js", "search/positions/application/restoration.js", "search/results/presentation/row.js", "search/results/application/interactions.js", @@ -270,20 +270,20 @@ function buildFiles(project) { return [ ...readerFiles, - "search/search-session.js", - "search/download-controller.js", + "search/execution/application/session.js", + "search/downloads/application/controller.js", "search/execution/domain/policy.js", "search/execution/application/controller.js", "search/downloads/application/batch.js", "search/downloads/presentation/queue.js", - "search/size-format.js", - "search/record-path.js", - "search/highlight.js", - "search/response-cache.js", - "search/file-types.js", - "search/response-validation.js", - "search/result-identity.js", - "search/folder-selection.js", + "search/results/presentation/size-format.js", + "search/catalog/domain/record-path.js", + "search/results/presentation/highlight.js", + "search/requests/infrastructure/response-cache.js", + "search/catalog/domain/file-types.js", + "search/requests/domain/response-validation.js", + "search/results/domain/result-identity.js", + "search/sidebar/domain/folder-selection.js", "search/input/domain/ownership.js", "search/input/application/controller.js", "search/results/domain/paging-policy.js", diff --git a/static/reader/ui/reader-speech.mjs b/static/reader/ui/reader-speech.mjs index d186e48977993d0089d370ebff3a87fc79fea18d..ceed533991957f390cc0fa75036845080411a1af 100644 --- a/static/reader/ui/reader-speech.mjs +++ b/static/reader/ui/reader-speech.mjs @@ -6,7 +6,7 @@ // the realm (frame document / shadow tree) that owns the range. const SKIP = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE"]); // A standalone Reader left while reading aloud (← or browser back) records -// where it was; search/reader-navigation.js resumes it in a background Reader +// where it was; search/reader-host/application/navigation.js resumes it in a background Reader // and passes the position through the frame name. Keep both keys in sync. const HANDOFF_KEY = "reader-speech-handoff"; const RESUME_PREFIX = "reader-speech-resume:"; diff --git a/static/search/file-types.js b/static/search/catalog/domain/file-types.js similarity index 100% rename from static/search/file-types.js rename to static/search/catalog/domain/file-types.js diff --git a/static/search/record-path.js b/static/search/catalog/domain/record-path.js similarity index 100% rename from static/search/record-path.js rename to static/search/catalog/domain/record-path.js diff --git a/static/search/download-controller.js b/static/search/downloads/application/controller.js similarity index 100% rename from static/search/download-controller.js rename to static/search/downloads/application/controller.js diff --git a/static/search/search-session.js b/static/search/execution/application/session.js similarity index 100% rename from static/search/search-session.js rename to static/search/execution/application/session.js diff --git a/static/search/reader-navigation.js b/static/search/reader-host/application/navigation.js similarity index 100% rename from static/search/reader-navigation.js rename to static/search/reader-host/application/navigation.js diff --git a/static/search/response-validation.js b/static/search/requests/domain/response-validation.js similarity index 100% rename from static/search/response-validation.js rename to static/search/requests/domain/response-validation.js diff --git a/static/search/response-cache.js b/static/search/requests/infrastructure/response-cache.js similarity index 100% rename from static/search/response-cache.js rename to static/search/requests/infrastructure/response-cache.js diff --git a/static/search/result-identity.js b/static/search/results/domain/result-identity.js similarity index 100% rename from static/search/result-identity.js rename to static/search/results/domain/result-identity.js diff --git a/static/search/highlight.js b/static/search/results/presentation/highlight.js similarity index 100% rename from static/search/highlight.js rename to static/search/results/presentation/highlight.js diff --git a/static/search/size-format.js b/static/search/results/presentation/size-format.js similarity index 100% rename from static/search/size-format.js rename to static/search/results/presentation/size-format.js diff --git a/static/search/folder-selection.js b/static/search/sidebar/domain/folder-selection.js similarity index 100% rename from static/search/folder-selection.js rename to static/search/sidebar/domain/folder-selection.js diff --git a/static/sw.js b/static/sw.js index 935acb45251e2f270f8216742209a7e56cd90e72..023019f2b5e033c4fd449d257eef244e8a3e5115 100644 --- a/static/sw.js +++ b/static/sw.js @@ -148,7 +148,7 @@ const PRECACHE_URLS = [ "/static/style.css", "/static/reader-resources.js", "/static/reader/core/reader-contract.js", - "/static/search/reader-navigation.js", + "/static/search/reader-host/application/navigation.js", "/static/search/reader-host/presentation/return-position.js", "/static/search/reader-host/application/host.js", "/static/search/positions/domain/policy.js", diff --git a/tests/backend/test_api_contract.py b/tests/backend/test_api_contract.py index 5749df47c6b68364b73e418b60c2aeb9c40a5d26..8850ec69cb65d1532a361121283bc18d6cff17f7 100644 --- a/tests/backend/test_api_contract.py +++ b/tests/backend/test_api_contract.py @@ -24,6 +24,20 @@ except ModuleNotFoundError as exc: # pragma: no cover IMPORT_ERROR = exc +class BackendCompatibilityTests(unittest.TestCase): + def test_moved_modules_share_canonical_identity_and_function_globals(self): + import importlib + from pathlib import Path + root = Path(__file__).resolve().parents[2] + moves = json.loads((root / 'quality/backend-path-migration.json').read_text())['moves'] + for old, target in moves.items(): + with self.subTest(module=old): + compatibility = importlib.import_module(old[:-3].replace('/', '.')) + canonical = importlib.import_module(target[:-3].replace('/', '.')) + self.assertIs(compatibility, canonical) + self.assertEqual(Path(canonical.__file__).resolve(), (root / target).resolve()) + + @unittest.skipIf(app is None, f"app dependencies unavailable: {IMPORT_ERROR}") class RandomResponseContractTests(unittest.IsolatedAsyncioTestCase): async def test_random_responses_match_fixed_original_bytes_headers_and_choice_inputs(self): diff --git a/tests/gates/test_lifespan_coverage_slice.py b/tests/gates/test_lifespan_coverage_slice.py index 123c62893421c2ea073acca2e367e899464cd0ab..43af094145c448500f48a06b4942aa5c0b549866 100644 --- a/tests/gates/test_lifespan_coverage_slice.py +++ b/tests/gates/test_lifespan_coverage_slice.py @@ -154,9 +154,9 @@ class TransportCoverageSliceTests(unittest.TestCase): debt = json.loads((live / 'quality/baselines/backend-coverage-debt.json').read_text()) migrated = transport_baseline(live, debt) self.assertNotIn('backend/app.py', migrated) # Entire refactored app now requires 100%. - self.assertEqual(migrated['backend/proxy_streams.py']['missing_lines'], []) - self.assertEqual(migrated['backend/proxy_streams.py']['missing_arcs'], []) - self.assertNotIn('backend/search_transport.py', migrated) + self.assertEqual(migrated['backend/shared/transport/streams.py']['missing_lines'], []) + self.assertEqual(migrated['backend/shared/transport/streams.py']['missing_arcs'], []) + self.assertNotIn('backend/search/http/body_limit.py', migrated) report = {'meta': {'branch_coverage': True}, 'files': {}} for source in [live / 'app.py', *sorted((live / 'backend').rglob('*.py'))]: name = source.relative_to(live).as_posix() @@ -219,7 +219,7 @@ class TransportCoverageSliceTests(unittest.TestCase): self.assertIn('independently pinned', result.stderr) with self.assertRaisesRegex(ValueError, 'independently pinned'): coverage_errors(live, report, weakened, weakened) - for name in ('backend/app.py', 'backend/proxy_streams.py', 'backend/search_transport.py'): + for name in ('backend/app.py', 'backend/shared/transport/streams.py', 'backend/search/http/body_limit.py'): for branch in (False, True): damaged = copy.deepcopy(report) item = damaged['files'][name] @@ -259,7 +259,7 @@ class TransportCoverageSliceTests(unittest.TestCase): return data + b'\n# tampered\n' if path == target else data from unittest.mock import patch with self.subTest(source=source), patch.object(Path, 'read_bytes', tampered): - with self.assertRaisesRegex(ValueError, 'exact reviewed source|independently pinned'): + with self.assertRaisesRegex(ValueError, 'exact reviewed source|exact canonical source|exact compatibility import|independently pinned'): transport_baseline(live, historical) @@ -279,14 +279,15 @@ class RefactorCoverageMigrationTests(unittest.TestCase): migrated = transport_baseline(live, debt) self.assertEqual(debt, original) self.assertFalse(set(manifest['sources']) & set(migrated)) - self.assertEqual(migrated, {name: entry for name, entry in old.items() if name != 'backend/app.py'}) + from scripts.backend_paths import migrate_paths + self.assertEqual(migrated, migrate_paths(live, {name: entry for name, entry in old.items() if name != 'backend/app.py'})) read_bytes = Path.read_bytes for source in manifest['sources']: def tampered(path, target=live / source): data = read_bytes(path) return data + b'\n# changed source\n' if path == target else data with self.subTest(source=source), patch.object(Path, 'read_bytes', tampered): - with self.assertRaisesRegex(ValueError, 'exact reviewed source'): + with self.assertRaisesRegex(ValueError, 'exact reviewed source|exact canonical source|exact compatibility import'): transport_baseline(live, debt) for field, coordinate in (('missing_lines', 1062), ('missing_arcs', [1062, 1063])): damaged = copy.deepcopy(old) @@ -334,9 +335,11 @@ ANCHORS = CATALOG_ROOT / 'scripts/coverage-anchors' class CatalogCoverageMigrationTests(unittest.TestCase): def test_mapping_preserves_parent_debt_and_rejects_suppression(self): parent = json.loads((ANCHORS / 'lifespan-parent-backend-coverage-debt.json').read_text()) - migrated = transport_baseline(CATALOG_ROOT, parent)[NAME] + from scripts.backend_paths import canonical_path, reviewed_source + target = canonical_path(CATALOG_ROOT, NAME).relative_to(CATALOG_ROOT).as_posix() + migrated = transport_baseline(CATALOG_ROOT, parent)[target] old = (ANCHORS / 'catalog-parent.py.snapshot').read_text().splitlines() - new = (CATALOG_ROOT / NAME).read_text().splitlines() + new = reviewed_source(CATALOG_ROOT, NAME).decode().splitlines() ops = difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes() mapping = {i + 1: j + 1 + i - start for op, start, end, j, _ in ops if op == 'equal' for i in range(start, end)} @@ -359,6 +362,7 @@ class CatalogCoverageMigrationTests(unittest.TestCase): parent = json.loads((ANCHORS / 'lifespan-parent-backend-coverage-debt.json').read_text()) with tempfile.TemporaryDirectory() as directory: root = Path(directory) + (root / 'quality').symlink_to(CATALOG_ROOT / 'quality', target_is_directory=True) (root / 'backend').symlink_to(CATALOG_ROOT / 'backend', target_is_directory=True) (root / 'scripts').mkdir() (root / 'scripts/coverage-anchors').mkdir() @@ -378,14 +382,16 @@ class CatalogCoverageMigrationTests(unittest.TestCase): catalog = root / NAME catalog.unlink() catalog.write_bytes((CATALOG_ROOT / NAME).read_bytes() + b'\n# tamper\n') - with self.assertRaisesRegex(ValueError, 'exact reviewed source'): + with self.assertRaisesRegex(ValueError, 'exact compatibility import'): transport_baseline(root, parent) @unittest.skipUnless(os.environ.get('CATALOG_COVERAGE_REPORT'), 'requires full coverage report') def test_report_rejects_suppressed_old_and_new_coverage(self): report = json.loads(Path(os.environ['CATALOG_COVERAGE_REPORT']).read_text()) parent = json.loads((ANCHORS / 'lifespan-parent-backend-coverage-debt.json').read_text()) - mapped = transport_baseline(CATALOG_ROOT, parent)[NAME] + from scripts.backend_paths import canonical_path + target = canonical_path(CATALOG_ROOT, NAME).relative_to(CATALOG_ROOT).as_posix() + mapped = transport_baseline(CATALOG_ROOT, parent)[target] self.assertFalse(coverage_errors(CATALOG_ROOT, report, parent)) for field, missing, count, coordinate, message in ( ('executed_lines', 'missing_lines', 'covered_lines', mapped['lines'][-1], 'previously covered lines'), @@ -394,11 +400,11 @@ class CatalogCoverageMigrationTests(unittest.TestCase): ('executed_branches', 'missing_branches', 'covered_branches', [100, 102], 'new or changed backend branches'), ): damaged = copy.deepcopy(report) - item = damaged['files'][NAME] + item = damaged['files'][target] item[field].remove(coordinate) item[missing].append(coordinate) item['summary'][count] -= 1 - self.assertTrue(any(message in error and NAME in error for error in coverage_errors(CATALOG_ROOT, damaged, parent))) + self.assertTrue(any(message in error and target in error for error in coverage_errors(CATALOG_ROOT, damaged, parent))) if __name__ == '__main__': diff --git a/tests/gates/test_mutation_gate_main.py b/tests/gates/test_mutation_gate_main.py index e7ea88613434037f384411f9b9ceb6482aadb481..4684ddff629ffe973b889a6c7ed17db7753b8964 100644 --- a/tests/gates/test_mutation_gate_main.py +++ b/tests/gates/test_mutation_gate_main.py @@ -24,11 +24,14 @@ class MutationGateMainTests(unittest.TestCase): (self.root / folder).mkdir(parents=True) (self.root / 'backend/__init__.py').write_text('') source = b'def synthetic(value):\n return value\n' - (self.root / 'backend/search_bootstrap.py').write_bytes(source) + for package in ('search', 'search/application'): + (self.root / 'backend' / package).mkdir(exist_ok=True) + (self.root / 'backend' / package / '__init__.py').write_text('') + (self.root / 'backend/search/application/bootstrap.py').write_bytes(source) (self.root / 'tests/search/backend').mkdir(parents=True) (self.root / 'tests/search/backend/test_search_bootstrap_mutation_contract.py').write_text('def test_fixture(): pass\n') (self.root / 'quality/mutation-reviews/mutation-equivalent-search-bootstrap.json').write_text(json.dumps({ - 'tool': 'mutmut 3.8.1', 'source': 'backend/search_bootstrap.py', + 'tool': 'mutmut 3.8.1', 'source': 'backend/search/application/bootstrap.py', 'source_sha256': hashlib.sha256(source).hexdigest(), 'equivalent': {}})) self.calls = [] self.outcome = 1 @@ -58,8 +61,7 @@ class MutationGateMainTests(unittest.TestCase): self.assertEqual([path.relative_to(cwd) for path in (Path(cwd) / 'static').rglob('*') if path.is_file()], [fixture]) self.assertEqual({path.name for path in Path(cwd).iterdir()}, expected_entries) - module_path = {'search_projection': 'search/domain/projection', - 'reader_identity': 'reader/query/domain/identity'}.get(self.module, self.module) + module_path = gate.MODULE_PATHS[self.module] if self.module == 'search_projection': self.assertEqual(self.configurations[-1]['tool']['mutmut']['only_mutate'], ['backend/search/domain/projection.py']) @@ -68,8 +70,8 @@ class MutationGateMainTests(unittest.TestCase): self.assertEqual((Path(cwd) / rel).read_bytes(), (self.root / rel).read_bytes()) self.assertEqual((Path(cwd) / 'tests/__init__.py').read_bytes(), b'') for dependency in gate.SPECS[self.module][2]: - self.assertEqual((Path(cwd) / 'backend' / dependency).read_bytes(), - (self.root / 'backend' / dependency).read_bytes()) + path = Path('backend') / (gate.MODULE_PATHS[Path(dependency).stem] + '.py') + self.assertEqual((Path(cwd) / path).read_bytes(), (self.root / path).read_bytes()) if self.module == 'reader_identity': self.assertEqual(self.configurations[-1]['tool']['mutmut']['only_mutate'], ['backend/reader/query/domain/identity.py']) @@ -78,8 +80,7 @@ class MutationGateMainTests(unittest.TestCase): 'tests/support/reader-contract-vectors.json'): self.assertEqual((Path(cwd) / rel).read_bytes(), (self.root / rel).read_bytes()) if command[-1] == 'export-cicd-stats': - module_path = {'search_projection': 'search/domain/projection', - 'reader_identity': 'reader/query/domain/identity'}.get(self.module, self.module) + module_path = gate.MODULE_PATHS[self.module] folder = Path(cwd) / 'mutants/backend' (folder / module_path).parent.mkdir(parents=True) stats = {'total': self.count, 'killed': int(self.outcome == 1), @@ -101,7 +102,7 @@ class MutationGateMainTests(unittest.TestCase): segment = ast.get_source_segment(self.generated, node) review_path = self.root / 'quality/mutation-reviews' / f'mutation-equivalent-{self.module.replace("_", "-")}.json' review = json.loads(review_path.read_text()) - review['equivalent'] = {f'backend.{self.module}.x_example__mutmut_1': { + review['equivalent'] = {f'backend.{gate.MODULE_PATHS[self.module].replace("/", ".")}.x_example__mutmut_1': { 'sha256': hashlib.sha256(segment.encode()).hexdigest(), 'rationale': 'synthetic review'}} review_path.write_text(json.dumps(review)) def version(name): @@ -121,14 +122,13 @@ class MutationGateMainTests(unittest.TestCase): self.args = ['--module', module] test_name, _, dependencies = gate.SPECS[module] source = b'def synthetic(value):\n return value\n' - module_path = {'search_projection': 'search/domain/projection', - 'reader_identity': 'reader/query/domain/identity'}.get(module, module) + module_path = gate.MODULE_PATHS[module] source_file = self.root / 'backend' / f'{module_path}.py' source_file.parent.mkdir(parents=True, exist_ok=True) source_file.write_bytes(source) - if module == 'search_projection': - for package in ('search', 'search/domain'): - (self.root / 'backend' / package / '__init__.py').write_text('') + for parent in source_file.relative_to(self.root).parents: + if parent != Path('.'): + (self.root / parent / '__init__.py').write_text('') target_test = self.root / 'tests' / test_name target_test.parent.mkdir(parents=True, exist_ok=True) target_test.write_text('def test_fixture(): pass\n') @@ -136,7 +136,12 @@ class MutationGateMainTests(unittest.TestCase): 'tool': 'mutmut 3.8.1', 'source': f'backend/{module_path}.py', 'source_sha256': hashlib.sha256(source).hexdigest(), 'equivalent': {}})) for dependency in dependencies: - (self.root / 'backend' / dependency).write_text(f'# synthetic dependency {dependency}\n') + path = self.root / 'backend' / (gate.MODULE_PATHS[Path(dependency).stem] + '.py') + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f'# synthetic dependency {dependency}\n') + for parent in path.relative_to(self.root).parents: + if parent != Path('.'): + (self.root / parent / '__init__.py').write_text('') if module == 'reader_identity': for package in ('reader', 'reader/query', 'reader/query/domain'): (self.root / 'backend' / package / '__init__.py').write_text('') @@ -165,12 +170,12 @@ class MutationGateMainTests(unittest.TestCase): (self.root / 'static/unrelated.js').write_text('must not be copied\n') result, stdout, stderr = self.run_main() self.assertEqual((result, stderr), (0, '')) - self.assertEqual(json.loads(stdout)['source'], 'backend/record_metadata.py') + self.assertEqual(json.loads(stdout)['source'], 'backend/search/corpus/domain/records.py') config = self.configurations[0]['tool']['mutmut'] # mutmut copies this directory into mutants/ before running the real # backend-to-frontend URL contract; the file alone has missing parents. self.assertEqual(config['also_copy'], ['static/']) - self.assertEqual(config['only_mutate'], ['backend/record_metadata.py']) + self.assertEqual(config['only_mutate'], ['backend/search/corpus/domain/records.py']) self.assertEqual(config['pytest_add_cli_args_test_selection'], ['tests/search/backend/test_record_metadata_contract.py']) @@ -188,7 +193,7 @@ class MutationGateMainTests(unittest.TestCase): self.assertEqual(list(reported), sorted(reported)) self.assertEqual((reported['total'], reported['killed'], reported['survived']), (1, 1, 0)) self.assertEqual(reported['tool'], 'mutmut 3.8.1') - self.assertEqual(reported['source'], 'backend/search_bootstrap.py') + self.assertEqual(reported['source'], 'backend/search/application/bootstrap.py') self.assertEqual(reported['source_sha256'], hashlib.sha256((self.root / reported['source']).read_bytes()).hexdigest()) self.assertEqual(reported['test'], 'search/backend/test_search_bootstrap_mutation_contract.py') self.assertEqual(reported['test_sha256'], hashlib.sha256((self.root / 'tests' / reported['test']).read_bytes()).hexdigest()) @@ -202,12 +207,12 @@ class MutationGateMainTests(unittest.TestCase): self.assertEqual(call[2]['PYTEST_DISABLE_PLUGIN_AUTOLOAD'], '1') self.assertTrue(all(call[3] and call[4] == 600 for call in self.calls)) self.assertEqual(self.configurations, [{'tool': {'mutmut': {'source_paths': ['backend/'], - 'only_mutate': ['backend/search_bootstrap.py'], + 'only_mutate': ['backend/search/application/bootstrap.py'], 'pytest_add_cli_args_test_selection': ['tests/search/backend/test_search_bootstrap_mutation_contract.py'], 'use_git_change_detection': False, 'use_setproctitle': False}}}]) def test_stale_source_review_fails_before_any_subprocess(self): - (self.root / 'backend/search_bootstrap.py').write_text('changed\n') + (self.root / 'backend/search/application/bootstrap.py').write_text('changed\n') result, _, stderr = self.run_main() self.assertEqual(result, 1) self.assertEqual(stderr, 'Mutation equivalent review must match the exact source and tool version\n') @@ -249,7 +254,7 @@ class MutationGateMainTests(unittest.TestCase): def test_failure_diagnostics_preserve_exact_values_and_error_separator(self): self.outcome = 0 self.count = 2 - key = 'backend.search_bootstrap.x_example__mutmut_1' + key = 'backend.search.application.bootstrap.x_example__mutmut_1' self.durations = {key: 1.25} self.estimates = {key: 0.125} result, _, stderr = self.run_main() @@ -276,7 +281,7 @@ class MutationGateMainTests(unittest.TestCase): def test_each_missing_optional_timing_field_still_reports_failure(self): self.outcome = 0 - key = 'backend.search_bootstrap.x_example__mutmut_1' + key = 'backend.search.application.bootstrap.x_example__mutmut_1' for present in ('durations_by_key', 'estimated_durations_by_key'): with self.subTest(present=present): self.timing_fields = {present} @@ -351,11 +356,11 @@ class MutationGateMainTests(unittest.TestCase): self.assertEqual(result, 1) report = json.loads(stdout) self.assertEqual((report['killed'], report['survived'], report['reviewed_equivalent_survivors']), (1, 0, 0)) - self.assertIn('stale equivalent-mutation review: backend.search_bootstrap.x_example__mutmut_1', stderr) + self.assertIn('stale equivalent-mutation review: backend.search.application.bootstrap.x_example__mutmut_1', stderr) def test_missing_generated_source_reports_the_mutant_name(self): self.outcome = 0 - key = 'backend.search_bootstrap.x_example__mutmut_1' + key = 'backend.search.application.bootstrap.x_example__mutmut_1' with patch.object(gate.ast, 'get_source_segment', return_value=None), \ self.assertRaises(RuntimeError) as raised: self.run_main() diff --git a/tests/gates/test_quality_inventory.py b/tests/gates/test_quality_inventory.py index 57f189d56fb77e4359455a14ac1ba9134210de07..8eba22895d305c6e08a0fd31476e87f79e06c080 100644 --- a/tests/gates/test_quality_inventory.py +++ b/tests/gates/test_quality_inventory.py @@ -317,6 +317,87 @@ class QualityInventoryTests(unittest.TestCase): def strict_errors(self): return inventory_errors(self.root, self.js_strict, self.js_basic, self.py_strict, self.debt) + def test_path_migration_preserves_all_coordinates_without_report_input(self): + from scripts.backend_paths import migration, migrate_paths, reviewed_source, validate_migration + project = Path(__file__).resolve().parents[2] + validate_migration(project) + manifest = migration(project) + entry = {'covered_lines': 2, 'covered_branches': 1, 'lines': [3, 9], + 'arcs': [[3, -2]], 'missing_lines': [7], 'missing_arcs': [[3, 7]]} + baseline = {name: dict(entry) for name in manifest['moves']} + mapped = migrate_paths(project, baseline) + self.assertEqual(mapped, {target: entry for target in manifest['moves'].values()}) + self.assertEqual(len(mapped), len(baseline)) + for name, record in manifest['sources'].items(): + self.assertEqual(hashlib.sha256(reviewed_source(project, name)).hexdigest(), record['before_sha256']) + self.assertEqual(len(reviewed_source(project, name).splitlines()), + len((project / record['target']).read_bytes().splitlines())) + + def test_path_migration_rejects_missing_and_tampered_proof_inputs(self): + from scripts.backend_paths import MAP_FILE, migrate_paths, migration + project = Path(__file__).resolve().parents[2] + manifest = migration(project) + for folder in ('backend', 'quality'): + shutil.copytree(project / folder, self.root / folder, dirs_exist_ok=True) + target = manifest['moves']['backend/search_execution.py'] + for name in (MAP_FILE, target, 'backend/search_execution.py'): + path = self.root / name + original = path.read_bytes() + for damaged in (None, original + b'\n# changed\n'): + with self.subTest(path=name, deleted=damaged is None): + if damaged is None: + path.unlink() + else: + path.write_bytes(damaged) + with self.assertRaises((ValueError, OSError)): + migrate_paths(self.root, {}) + path.write_bytes(original) + # Editing an import and its manifest cannot mint a new reviewed proof. + path = self.root / MAP_FILE + changed = json.loads(path.read_text()) + changed['sources']['backend/search_term_candidates.py']['imports'][0][2] = 'from arbitrary import execute\n' + path.write_text(json.dumps(changed)) + with self.assertRaisesRegex(ValueError, 'exact reviewed mapping'): + migrate_paths(self.root, {}) + + def test_compatibility_identity_and_shared_state_in_both_import_orders(self): + project = Path(__file__).resolve().parents[2] + probe = ''' +import importlib, inspect, json, sys, threading +from pathlib import Path +mapping = json.loads(Path('quality/backend-path-migration.json').read_text())['moves'] +for old, target in mapping.items(): + names = [old[:-3].replace('/', '.'), target[:-3].replace('/', '.')] + if sys.argv[1] == 'canonical': + names.reverse() + first, second = (importlib.import_module(name) for name in names) + assert first is second, names + assert Path(first.__file__).resolve() == Path(target).resolve(), names + for value in vars(first).values(): + if inspect.isfunction(value) and value.__module__ == first.__name__: + assert Path(inspect.getsourcefile(value)).resolve() == Path(target).resolve() +from backend import search_execution as old_executor, upstream_http as old_upstream +from backend.search.infrastructure import executor +from backend.shared.transport import upstream +assert old_executor._search_thread is executor._search_thread +executor._search_thread.cancelled = threading.Event() +executor._search_thread.cancelled.set() +try: + old_executor.check_search_cancelled() +except old_executor.SearchCancelled: + pass +else: + raise AssertionError('thread-local cancellation was not shared') +replacement = {} +old_upstream.upstream_redirect_cache = replacement +assert upstream.upstream_redirect_cache is replacement +''' + for order in ('canonical', 'legacy'): + with self.subTest(order=order): + result = subprocess.run([sys.executable, '-B', '-c', probe, order], cwd=project, + capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_reader_identity_domain_is_strict_and_cannot_be_omitted(self): project = Path(__file__).resolve().parents[2] config = json.loads((project / 'pyrightconfig.strict.json').read_text()) @@ -610,7 +691,7 @@ class QualityInventoryTests(unittest.TestCase): # absent from debt and are tested by the search-release migration test. # The vocabulary candidate module still requires complete coverage. root = Path(__file__).resolve().parents[2] - source = 'backend/search_term_candidates.py' + source = 'backend/search/domain/term_candidates.py' item = file_report(covered=1, statements=2, covered_branches=1, branches=2) item['missing_lines'] = [118] item['missing_branches'] = [[117, 118]] @@ -1503,13 +1584,13 @@ class Example: root = Path(__file__).resolve().parents[2] review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-proxy-streams.json").read_text()) self.assertEqual(review["tool"], "mutmut 3.8.1") - self.assertEqual(review["source"], "backend/proxy_streams.py") + self.assertEqual(review["source"], "backend/shared/transport/streams.py") self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest()) self.assertTrue(review["scope"]) - self.assertNotIn("backend.proxy_streams.xǁRangeSubscriptionǁstream__mutmut_13", review["equivalent"]) + self.assertNotIn("backend.shared.transport.streams.xǁRangeSubscriptionǁstream__mutmut_13", review["equivalent"]) for name, entry in review["equivalent"].items(): with self.subTest(mutant=name): - self.assertTrue(name.startswith("backend.proxy_streams.")) + self.assertTrue(name.startswith("backend.shared.transport.streams.")) self.assertRegex(entry["sha256"], r"^[0-9a-f]{64}$") self.assertTrue(entry["rationale"]) @@ -1518,12 +1599,12 @@ class Example: root = Path(__file__).resolve().parents[2] review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-folder-tree.json").read_text()) self.assertEqual(review["tool"], "mutmut 3.8.1") - self.assertEqual(review["source"], "backend/folder_tree.py") + self.assertEqual(review["source"], "backend/search/corpus/domain/folder_tree.py") self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest()) self.assertTrue(review["scope"]) for name, entry in review["equivalent"].items(): with self.subTest(mutant=name): - self.assertTrue(name.startswith("backend.folder_tree.")) + self.assertTrue(name.startswith("backend.search.corpus.domain.folder_tree.")) self.assertRegex(entry["sha256"], r"^[0-9a-f]{64}$") self.assertTrue(entry["rationale"]) @@ -1547,12 +1628,12 @@ class Example: root = Path(__file__).resolve().parents[2] review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-search-candidates.json").read_text()) self.assertEqual(review["tool"], "mutmut 3.8.1") - self.assertEqual(review["source"], "backend/search_candidates.py") + self.assertEqual(review["source"], "backend/search/domain/candidates.py") self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest()) self.assertTrue(review["scope"]) for name, entry in review["equivalent"].items(): with self.subTest(mutant=name): - self.assertTrue(name.startswith("backend.search_candidates.")) + self.assertTrue(name.startswith("backend.search.domain.candidates.")) self.assertRegex(entry["sha256"], r"^[0-9a-f]{64}$") self.assertTrue(entry["rationale"]) @@ -1561,7 +1642,7 @@ class Example: root = Path(__file__).resolve().parents[2] review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-reader-archive.json").read_text()) self.assertEqual(review["tool"], "mutmut 3.8.1") - self.assertEqual(review["source"], "backend/reader_archive.py") + self.assertEqual(review["source"], "backend/reader/archive/domain/validation.py") self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest()) self.assertTrue(review["scope"]) contract = (root / "tests" / SPECS["reader_archive"][0]).read_text() @@ -1570,7 +1651,7 @@ class Example: self.assertNotIn("backend.app", contract) for name, entry in review["equivalent"].items(): with self.subTest(mutant=name): - self.assertTrue(name.startswith("backend.reader_archive.")) + self.assertTrue(name.startswith("backend.reader.archive.domain.validation.")) self.assertRegex(entry["sha256"], r"^[0-9a-f]{64}$") self.assertTrue(entry["rationale"]) @@ -2876,7 +2957,7 @@ class Example: root = Path(__file__).resolve().parents[2] review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-search-browse.json").read_text()) self.assertEqual(review["tool"], "mutmut 3.8.1") - self.assertEqual(review["source"], "backend/search_browse.py") + self.assertEqual(review["source"], "backend/search/domain/browse.py") self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest()) self.assertTrue(review["scope"]) self.assertEqual(review["equivalent"], {}) @@ -2889,12 +2970,12 @@ class Example: root = Path(__file__).resolve().parents[2] review = json.loads((root / "quality/mutation-reviews/mutation-equivalent-search-bootstrap.json").read_text()) self.assertEqual(review["tool"], "mutmut 3.8.1") - self.assertEqual(review["source"], "backend/search_bootstrap.py") + self.assertEqual(review["source"], "backend/search/application/bootstrap.py") self.assertEqual(review["source_sha256"], hashlib.sha256((root / review["source"]).read_bytes()).hexdigest()) self.assertTrue(review["scope"]) for name, entry in review["equivalent"].items(): with self.subTest(mutant=name): - self.assertTrue(name.startswith("backend.search_bootstrap.")) + self.assertTrue(name.startswith("backend.search.application.bootstrap.")) self.assertRegex(entry["sha256"], r"^[0-9a-f]{64}$") self.assertTrue(entry["rationale"]) diff --git a/tests/gates/test_static_checks.py b/tests/gates/test_static_checks.py index a41d9385ab13acd620f941d4cf28b2ca210e10f0..a787be7d2d9808fde5f680b56243a858467a07d1 100644 --- a/tests/gates/test_static_checks.py +++ b/tests/gates/test_static_checks.py @@ -293,7 +293,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "coverage") def test_download_controller_coverage_gate_fails_closed(self): - paths = ["static/search/download-controller.js", "scripts/search/check_download_controller_coverage.mjs", + paths = ["static/search/downloads/application/controller.js", "scripts/search/check_download_controller_coverage.mjs", "scripts/check_tap_contracts.mjs", "tests/search/download/test_download_controller_contract.js", "static/search/downloads/application/batch.js", "static/search/downloads/presentation/queue.js", "static/app.js"] for relative in paths: @@ -301,7 +301,7 @@ class StaticGateTests(unittest.TestCase): target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / relative, target) check = ["node", paths[1]] - self.assert_check(self.run_check(*check), True, "download-controller.js") + self.assert_check(self.run_check(*check), True, "controller.js") contract = self.root / paths[3] original = contract.read_text() names = re.findall(r'^test\("([^"\n]+)"', original, re.M) @@ -336,11 +336,11 @@ class StaticGateTests(unittest.TestCase): original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) for name in ("jsconfig.strict.json", "jsconfig.search-exact.json"): - self.assertIn("static/search/download-controller.js", load_type_config(name)["files"]) + self.assertIn("static/search/downloads/application/controller.js", load_type_config(name)["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "noUncheckedIndexedAccess": True, "exactOptionalPropertyTypes": True, "target": "esnext", "module": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/download-controller.js")]})) + "files": [str(declaration), str(ROOT / "static/search/downloads/application/controller.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") before = "checkDownload(link: string, speculative?: boolean, signal?: AbortSignal): Promise;" @@ -422,7 +422,7 @@ class StaticGateTests(unittest.TestCase): def test_search_response_cache_coverage_gate_fails_closed(self): - paths = ["static/search/response-cache.js", "scripts/search/check_search_response_cache_coverage.mjs", + paths = ["static/search/requests/infrastructure/response-cache.js", "scripts/search/check_search_response_cache_coverage.mjs", "tests/search/response-cache/test_search_response_cache_contract.js"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -463,14 +463,14 @@ class StaticGateTests(unittest.TestCase): test.write_text(original + "\n" + extra + "\n") result = self.run_check(*check) self.assert_check(result, False, "exactly one fully covered source row") - self.assertIn("# response-cache.js | 100.00", result.stdout) + self.assertIn("# response-cache.js | 100.00", result.stdout) self.assertEqual(result.stdout.count("response-cache.js |"), 2) test.write_text('require("node:test")("empty", () => {});\n') self.assert_check(self.run_check(*check), False, "exactly one fully covered source row") test.write_text('throw new Error("failed response cache test");\n') self.assert_check(self.run_check(*check), False, "failed response cache test") test.write_text('const vm = require("vm"), fs = require("fs");\n' - 'const filename = process.cwd() + "/static/search/response-cache.js";\n' + 'const filename = process.cwd() + "/static/search/requests/infrastructure/response-cache.js";\n' 'vm.runInNewContext(fs.readFileSync(filename, "utf8"), {}, {filename});\n') self.assert_check(self.run_check(*check), False, "coverage") @@ -479,10 +479,10 @@ class StaticGateTests(unittest.TestCase): declaration = self.root / "reader-globals.d.ts" original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) - self.assertIn("static/search/response-cache.js", load_type_config("jsconfig.strict.json")["files"]) + self.assertIn("static/search/requests/infrastructure/response-cache.js", load_type_config("jsconfig.strict.json")["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/response-cache.js")]})) + "files": [str(declaration), str(ROOT / "static/search/requests/infrastructure/response-cache.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") before = " constructor(limit: number, ttl: number, budget?: number);" @@ -506,7 +506,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "TS2322") def test_search_result_identity_coverage_gate_fails_closed(self): - paths = ["static/search/result-identity.js", "static/search/record-path.js", + paths = ["static/search/results/domain/result-identity.js", "static/search/catalog/domain/record-path.js", "scripts/search/check_search_result_identity_coverage.mjs", "tests/search/baselines/test_search_stable_id_baseline.mjs", "static/app.js"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -534,7 +534,7 @@ class StaticGateTests(unittest.TestCase): test.write_text(source) gate = self.root / paths[2] gate_source = gate.read_text() - include = "--test-coverage-include=**/static/search/result-identity.js" + include = "--test-coverage-include=**/static/search/results/domain/result-identity.js" self.assertEqual(gate_source.count(include), 1) gate.write_text(gate_source.replace(include, "--test-coverage-include=**/missing-identity.js")) self.assert_check(self.run_check(*check), False, "exactly one fully covered source row") @@ -544,10 +544,10 @@ class StaticGateTests(unittest.TestCase): declaration = self.root / "reader-globals.d.ts" original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) - self.assertIn("static/search/result-identity.js", load_type_config("jsconfig.strict.json")["files"]) + self.assertIn("static/search/results/domain/result-identity.js", load_type_config("jsconfig.strict.json")["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/result-identity.js")]})) + "files": [str(declaration), str(ROOT / "static/search/results/domain/result-identity.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") before = "declare var VoiceOfMLSearchIdentity: {getResultStableId(result: unknown): string};" @@ -569,7 +569,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "TS2322") def test_search_folder_selection_coverage_gate_fails_closed(self): - paths = ["static/search/folder-selection.js", "scripts/search/check_search_folder_selection_coverage.mjs", + paths = ["static/search/sidebar/domain/folder-selection.js", "scripts/search/check_search_folder_selection_coverage.mjs", "tests/search/baselines/test_search_folder_selection_baseline.mjs"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -605,7 +605,7 @@ class StaticGateTests(unittest.TestCase): module.write_text(module_source) gate = self.root / paths[1] gate_source = gate.read_text() - include = "--test-coverage-include=**/static/search/folder-selection.js" + include = "--test-coverage-include=**/static/search/sidebar/domain/folder-selection.js" self.assertEqual(gate_source.count(include), 1) gate.write_text(gate_source.replace(include, "--test-coverage-include=**/missing-folder-selection.js")) self.assert_check(self.run_check(*check), False, "exactly one fully covered source row") @@ -616,11 +616,11 @@ class StaticGateTests(unittest.TestCase): original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) for name in ("jsconfig.strict.json", "jsconfig.search-exact.json", "jsconfig.check.json"): - self.assertIn("static/search/folder-selection.js", load_type_config(name)["files"]) + self.assertIn("static/search/sidebar/domain/folder-selection.js", load_type_config(name)["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "noUncheckedIndexedAccess": True, "exactOptionalPropertyTypes": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/folder-selection.js")]})) + "files": [str(declaration), str(ROOT / "static/search/sidebar/domain/folder-selection.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") before = " folderPathCovered(path: string, subtreeSet: ReadonlySet): boolean;" @@ -1211,7 +1211,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, diagnostic) def test_search_response_validation_coverage_gate_fails_closed(self): - paths = ["static/search/response-validation.js", "scripts/search/check_search_response_validation_coverage.mjs", + paths = ["static/search/requests/domain/response-validation.js", "scripts/search/check_search_response_validation_coverage.mjs", "tests/search/baselines/test_search_response_validation_baseline.mjs", "static/app.js"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -1240,7 +1240,7 @@ class StaticGateTests(unittest.TestCase): test.write_text(source) gate = self.root / paths[1] gate_source = gate.read_text() - include = "--test-coverage-include=**/static/search/response-validation.js" + include = "--test-coverage-include=**/static/search/requests/domain/response-validation.js" self.assertEqual(gate_source.count(include), 1) gate.write_text(gate_source.replace(include, "--test-coverage-include=**/missing-validator.js")) self.assert_check(self.run_check(*check), False, "exactly one fully covered source row") @@ -1250,10 +1250,10 @@ class StaticGateTests(unittest.TestCase): declaration = self.root / "reader-globals.d.ts" original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) - self.assertIn("static/search/response-validation.js", load_type_config("jsconfig.strict.json")["files"]) + self.assertIn("static/search/requests/domain/response-validation.js", load_type_config("jsconfig.strict.json")["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/response-validation.js")]})) + "files": [str(declaration), str(ROOT / "static/search/requests/domain/response-validation.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") for before, after in [("expectedPage: number, expectedPageSize: number): unknown", @@ -1286,7 +1286,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), True, "") def test_search_file_types_coverage_gate_fails_closed(self): - paths = ["static/search/file-types.js", "scripts/search/check_search_file_types_coverage.mjs", + paths = ["static/search/catalog/domain/file-types.js", "scripts/search/check_search_file_types_coverage.mjs", "tests/search/baselines/test_search_extension_inventory_baseline.mjs", "static/app.js"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -1306,7 +1306,7 @@ class StaticGateTests(unittest.TestCase): test.write_text('throw new Error("failed file types test");\n') self.assert_check(self.run_check(*check), False, "failed file types test") test.write_text('import vm from "node:vm"; import fs from "node:fs";\n' - 'const filename = process.cwd() + "/static/search/file-types.js";\n' + 'const filename = process.cwd() + "/static/search/catalog/domain/file-types.js";\n' 'vm.runInNewContext(fs.readFileSync(filename, "utf8"), {}, {filename});\n') self.assert_check(self.run_check(*check), False, "coverage") names = ["all 67 ordered filter extensions are pinned, including case-sensitive lookup", @@ -1316,7 +1316,7 @@ class StaticGateTests(unittest.TestCase): "const bindings retain their original mutable array and map contents", "inventory data is isolated between script evaluations"] test.write_text('import vm from "node:vm"; import fs from "node:fs"; import test from "node:test";\n' - 'const filename=process.cwd()+"/static/search/file-types.js";\n' + 'const filename=process.cwd()+"/static/search/catalog/domain/file-types.js";\n' 'vm.runInNewContext(fs.readFileSync(filename,"utf8"),{}, {filename});\n' + '\n'.join('test.skip(' + json.dumps(name) + ', () => {});' for name in names)) self.assert_check(self.run_check(*check), False, "coverage") @@ -1326,10 +1326,10 @@ class StaticGateTests(unittest.TestCase): declaration = self.root / "reader-globals.d.ts" original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) - self.assertIn("static/search/file-types.js", load_type_config("jsconfig.strict.json")["files"]) + self.assertIn("static/search/catalog/domain/file-types.js", load_type_config("jsconfig.strict.json")["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/file-types.js")]})) + "files": [str(declaration), str(ROOT / "static/search/catalog/domain/file-types.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") for before, after in [ @@ -1341,7 +1341,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "TS2322") def test_search_highlight_coverage_gate_fails_closed(self): - paths = ["static/search/highlight.js", "scripts/search/check_search_highlight_coverage.mjs", + paths = ["static/search/results/presentation/highlight.js", "scripts/search/check_search_highlight_coverage.mjs", "tests/search/highlight/test_search_highlight_contract.js"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -1373,12 +1373,12 @@ class StaticGateTests(unittest.TestCase): test.write_text('throw new Error("failed highlight test");\n') self.assert_check(self.run_check(*check), False, "failed highlight test") test.write_text('const vm = require("vm"), fs = require("fs");\n' - 'const filename = process.cwd() + "/static/search/highlight.js";\n' + 'const filename = process.cwd() + "/static/search/results/presentation/highlight.js";\n' 'vm.runInNewContext(fs.readFileSync(filename, "utf8"), {}, {filename});\n') self.assert_check(self.run_check(*check), False, "coverage") def test_search_highlight_coverage_checks_fractional_minimum(self): - for path in ("static/search/highlight.js", "scripts/search/check_search_highlight_coverage.mjs", + for path in ("static/search/results/presentation/highlight.js", "scripts/search/check_search_highlight_coverage.mjs", "tests/search/highlight/test_search_highlight_contract.js", "scripts/check_tap_contracts.mjs"): target = self.root / path target.parent.mkdir(parents=True, exist_ok=True) @@ -1395,10 +1395,10 @@ class StaticGateTests(unittest.TestCase): declaration = self.root / "reader-globals.d.ts" original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) - self.assertIn("static/search/highlight.js", load_type_config("jsconfig.strict.json")["files"]) + self.assertIn("static/search/results/presentation/highlight.js", load_type_config("jsconfig.strict.json")["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/highlight.js")]})) + "files": [str(declaration), str(ROOT / "static/search/results/presentation/highlight.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") for before, after in [ @@ -1416,7 +1416,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "TS2322") def test_search_record_path_coverage_gate_fails_closed(self): - paths = ["static/search/record-path.js", "scripts/search/check_search_record_path_coverage.mjs", + paths = ["static/search/catalog/domain/record-path.js", "scripts/search/check_search_record_path_coverage.mjs", "tests/search/record-path/test_search_record_path.js", "static/app.js"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -1446,7 +1446,7 @@ class StaticGateTests(unittest.TestCase): test.write_text('throw new Error("failed path test");\n') self.assert_check(self.run_check(*check), False, "failed path test") test.write_text('const vm = require("vm"), fs = require("fs");\n' - 'const filename = process.cwd() + "/static/search/record-path.js";\n' + 'const filename = process.cwd() + "/static/search/catalog/domain/record-path.js";\n' 'vm.runInNewContext(fs.readFileSync(filename, "utf8"), {}, {filename});\n') self.assert_check(self.run_check(*check), False, "coverage") @@ -1455,10 +1455,10 @@ class StaticGateTests(unittest.TestCase): declaration = self.root / "reader-globals.d.ts" original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) - self.assertIn("static/search/record-path.js", load_type_config("jsconfig.strict.json")["files"]) + self.assertIn("static/search/catalog/domain/record-path.js", load_type_config("jsconfig.strict.json")["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/record-path.js")]})) + "files": [str(declaration), str(ROOT / "static/search/catalog/domain/record-path.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") for before, after in [ @@ -1472,7 +1472,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "TS2322") def test_search_size_coverage_gate_fails_closed(self): - paths = ["static/search/size-format.js", "scripts/search/check_search_size_coverage.mjs", + paths = ["static/search/results/presentation/size-format.js", "scripts/search/check_search_size_coverage.mjs", "tests/search/size/test_search_size_format.js", "tests/search/size/test_search_size_render_contract.js"] for path in [*paths, "scripts/check_tap_contracts.mjs"]: target = self.root / path @@ -1527,7 +1527,7 @@ class StaticGateTests(unittest.TestCase): config = self.root / "jsconfig.json" config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/size-format.js")]})) + "files": [str(declaration), str(ROOT / "static/search/results/presentation/size-format.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") before = "declare function formatSize(bytes: number | string | null | undefined): string | object | undefined;" @@ -1608,7 +1608,7 @@ class StaticGateTests(unittest.TestCase): declaration.write_text(original) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/size-format.js")]})) + "files": [str(declaration), str(ROOT / "static/search/results/presentation/size-format.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") before = "declare function fmtSizeUrl(bytes: number | null | undefined): string | null;" @@ -2042,10 +2042,10 @@ class StaticGateTests(unittest.TestCase): declaration = self.root / "reader-globals.d.ts" original = (ROOT / "typings/reader-globals.d.ts").read_text() declaration.write_text(original) - self.assertIn("static/search/search-session.js", load_type_config("jsconfig.strict.json")["files"]) + self.assertIn("static/search/execution/application/session.js", load_type_config("jsconfig.strict.json")["files"]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": True, "target": "esnext", "moduleDetection": "force"}, - "files": [str(declaration), str(ROOT / "static/search/search-session.js")]})) + "files": [str(declaration), str(ROOT / "static/search/execution/application/session.js")]})) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") for before, after in [ @@ -2058,7 +2058,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "TS2322") declaration.write_text(original) implementation = self.root / "static/search-session.js" - source = (ROOT / "static/search/search-session.js").read_text() + source = (ROOT / "static/search/execution/application/session.js").read_text() before = "return { openSearchSessionDB, persistSearchSession, restoreSearchSession };" self.assertEqual(source.count(before), 1) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, @@ -2123,9 +2123,9 @@ class StaticGateTests(unittest.TestCase): # Compile an isolated physical copy of the implementation with the # production exact options; a permissive declaration alone cannot pass. - implementation = self.root / "static/search/reader-navigation.js" + implementation = self.root / "static/search/reader-host/application/navigation.js" implementation.parent.mkdir(parents=True, exist_ok=True) - body = (ROOT / "static/search/reader-navigation.js").read_text() + body = (ROOT / "static/search/reader-host/application/navigation.js").read_text() implementation.write_text(body) declarations = ROOT / "typings/reader-globals.d.ts" config.write_text(json.dumps({"compilerOptions": original["compilerOptions"], @@ -2146,7 +2146,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "TS2322") def test_reader_navigation_baseline_gate_fails_closed(self): - paths = ["static/search/reader-navigation.js", "scripts/search/check_reader_navigation_baseline.mjs", + paths = ["static/search/reader-host/application/navigation.js", "scripts/search/check_reader_navigation_baseline.mjs", "tests/search/reader-navigation/test_reader_navigation_baseline.mjs", "scripts/check_tap_contracts.mjs"] for path in paths: target = self.root / path @@ -2185,7 +2185,7 @@ class StaticGateTests(unittest.TestCase): self.assert_check(self.run_check(*check), False, "all named baseline contracts") def test_reader_navigation_coverage_gate_requires_exact_source_row_and_thresholds(self): - paths = ["static/search/reader-navigation.js", "scripts/search/check_reader_navigation_baseline.mjs", + paths = ["static/search/reader-host/application/navigation.js", "scripts/search/check_reader_navigation_baseline.mjs", "tests/search/reader-navigation/test_reader_navigation_baseline.mjs", "scripts/check_tap_contracts.mjs"] for path in paths: target = self.root / path @@ -2194,7 +2194,7 @@ class StaticGateTests(unittest.TestCase): gate = self.root / paths[1] original = gate.read_text() check = ["node", paths[1]] - self.assert_check(self.run_check(*check), True, "reader-navigation.js |") + self.assert_check(self.run_check(*check), True, "navigation.js |") # Keep the real subprocess and TAP report but reject its parsed row. anchor = 'const rows = text.split(/\\r?\\n/).flatMap(line => {' self.assertEqual(original.count(anchor), 1) @@ -2973,9 +2973,9 @@ class StaticGateTests(unittest.TestCase): options = original["compilerOptions"] for flag in ("allowJs", "checkJs", "noEmit", "strict", "noUncheckedIndexedAccess", "exactOptionalPropertyTypes"): self.assertIs(options.get(flag), True, flag) - required = {"static/search/search-session.js", "static/search/reader-navigation.js", "static/search/download-controller.js", "static/search/result-identity.js", "static/search/record-path.js", - "static/search/folder-selection.js", "static/search/domain/height-index.js", "static/search/domain/stable-stringify.js", "static/search/domain/search-view-key.js", "static/search/domain/search-recovery.js", "static/search/domain/search-window-page.js", "static/search/presentation/sidebar-render.js", "static/search/response-validation.js", "static/search/response-cache.js", "static/search/file-types.js", - "static/search/highlight.js", "static/search/size-format.js"} + required = {"static/search/execution/application/session.js", "static/search/reader-host/application/navigation.js", "static/search/downloads/application/controller.js", "static/search/results/domain/result-identity.js", "static/search/catalog/domain/record-path.js", + "static/search/sidebar/domain/folder-selection.js", "static/search/domain/height-index.js", "static/search/domain/stable-stringify.js", "static/search/domain/search-view-key.js", "static/search/domain/search-recovery.js", "static/search/domain/search-window-page.js", "static/search/presentation/sidebar-render.js", "static/search/requests/domain/response-validation.js", "static/search/requests/infrastructure/response-cache.js", "static/search/catalog/domain/file-types.js", + "static/search/results/presentation/highlight.js", "static/search/results/presentation/size-format.js"} required.update({ "static/search/input/domain/ownership.js", "static/search/input/application/controller.js", @@ -3073,19 +3073,19 @@ class StaticGateTests(unittest.TestCase): shutil.copyfile(ROOT / name, target) production_check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", local_config] self.assert_check(self.run_check(*production_check), True, "") - module = self.root / "static/search/result-identity.js" + module = self.root / "static/search/results/domain/result-identity.js" module.write_text(module.read_text() + '\n/** @param {string[]} values @returns {string} */ function probe(values) { return values[0]; }\n') self.assert_check(self.run_check(*production_check), False, "TS2322") - shutil.copyfile(ROOT / "static/search/result-identity.js", module) - module = self.root / "static/search/highlight.js" + shutil.copyfile(ROOT / "static/search/results/domain/result-identity.js", module) + module = self.root / "static/search/results/presentation/highlight.js" module.write_text(module.read_text() + '\n/** @param {string[]} values @returns {string} */ function probe(values) { return values[0]; }\n') self.assert_check(self.run_check(*production_check), False, "TS2322") - shutil.copyfile(ROOT / "static/search/highlight.js", module) - module = self.root / "static/search/size-format.js" + shutil.copyfile(ROOT / "static/search/results/presentation/highlight.js", module) + module = self.root / "static/search/results/presentation/size-format.js" module.write_text(module.read_text() + '\n/** @param {string[]} values @returns {string} */ function probe(values) { return values[0]; }\n') self.assert_check(self.run_check(*production_check), False, "TS2322") - shutil.copyfile(ROOT / "static/search/size-format.js", module) - module = self.root / "static/search/download-controller.js" + shutil.copyfile(ROOT / "static/search/results/presentation/size-format.js", module) + module = self.root / "static/search/downloads/application/controller.js" module.write_text(module.read_text() + '\n/** @param {string[]} values @returns {string} */ function probe(values) { return values[0]; }\n') self.assert_check(self.run_check(*production_check), False, "TS2322") @@ -3099,7 +3099,7 @@ class StaticGateTests(unittest.TestCase): shutil.copyfile(ROOT / name, target) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") - module = self.root / "static/search/size-format.js" + module = self.root / "static/search/results/presentation/size-format.js" source = module.read_text() assertions = [('/** @type {string} */ (m[1])', 'm[1]', "TS2345"), ('@returns {string | object | undefined}', '@returns {string | object}', "TS2322")] @@ -3118,7 +3118,7 @@ class StaticGateTests(unittest.TestCase): shutil.copyfile(ROOT / name, target) check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") - module = self.root / "static/search/highlight.js" + module = self.root / "static/search/results/presentation/highlight.js" source = module.read_text() assertion = '/** @type {string} */ (HTML_ESCAPE_MAP[ch])' self.assertEqual(source.count(assertion), 1) @@ -4713,9 +4713,9 @@ for (const [project, base] of [['github','/search/static/'], ['hf','/static/']]) config.write_text(json.dumps({"compilerOptions": {"allowJs": True, "checkJs": True, "noEmit": True, "strict": False, "skipLibCheck": True, "target": "esnext", "moduleDetection": "force"}, "files": [str(ROOT / "typings/reader-globals.d.ts"), - str(ROOT / "static/search/search-session.js"), - str(ROOT / "static/search/download-controller.js"), - str(ROOT / "static/search/reader-navigation.js"), "static/global-contract.js"]})) + str(ROOT / "static/search/execution/application/session.js"), + str(ROOT / "static/search/downloads/application/controller.js"), + str(ROOT / "static/search/reader-host/application/navigation.js"), "static/global-contract.js"]})) source.write_text("console.log('contracts loaded');\n") check = ["node", ROOT / "node_modules/typescript/bin/tsc", "--project", config] self.assert_check(self.run_check(*check), True, "") @@ -4884,6 +4884,14 @@ for (const [project, base] of [['github','/search/static/'], ['hf','/static/']]) check = ["node", ROOT / "node_modules/pyright/index.js", "--pythonpath", sys.executable, "--project", "pyrightconfig.strict.json"] self.assert_check(self.run_check(*check), True, "0 errors") + # Probe the real moved implementations, not only their compatibility imports. + moves = json.loads((ROOT / 'quality/backend-path-migration.json').read_text())['moves'] + for relative in moves.values(): + source = self.root / relative + self.assertIn(relative, config['include']) + source.write_text(source.read_text() + '\ndef strict_canonical_probe(value):\n return value\n') + self.assert_check(self.run_check(*check), False, 'reportUnknownParameterType') + shutil.copyfile(ROOT / relative, source) source = self.root / "backend/search_execution.py" source.write_text(source.read_text() + "\ndef strict_probe(value):\n return value\n") self.assert_check(self.run_check(*check), False, "reportUnknownParameterType") diff --git a/tests/gates/test_static_contract.py b/tests/gates/test_static_contract.py index dd05f04d0df691108c23130da1fc9fc41bd901b5..3a992bd9337108247c569ab1f2d535782b493bfb 100644 --- a/tests/gates/test_static_contract.py +++ b/tests/gates/test_static_contract.py @@ -539,12 +539,12 @@ console.log('Chapter adapter contract passed; 5 negative controls rejected'); self.assertIn("deps.navigateToReader(actionBtn.dataset.readerUrl)", self.result_interactions) self.assertIn("const readerLink = browserItem.dataset.readUrl", self.result_interactions) self.assertIn("deps.navigateToReader(readerLink)", self.result_interactions) - navigation = (ROOT / "static/search/reader-navigation.js").read_text(encoding="utf-8") + navigation = (ROOT / "static/search/reader-host/application/navigation.js").read_text(encoding="utf-8") self.assertIn('url.searchParams.set("return", returnUrl)', navigation) self.assertIn('sessionStorage.setItem("reader-return:" + token', navigation) self.assertIn('crypto.getRandomValues(new Uint32Array(4))', navigation) - self.assertIn('search/reader-navigation.js', self.html) - self.assertIn('search/reader-navigation.js', self.sw) + self.assertIn('search/reader-host/application/navigation.js', self.html) + self.assertIn('search/reader-host/application/navigation.js', self.sw) self.assertNotIn("openPendingWindow", self.js) assert_source_contains(self, 'new URL(returnUrl, location.origin)', reader) assert_source_contains(self, 'sessionStorage.removeItem(returnHistoryKey)', reader) diff --git a/tests/reader/browser/test_reader_close_traffic.py b/tests/reader/browser/test_reader_close_traffic.py index ccdcf11a290c63e22d397e6b8c19c72ce6325f79..7f7e691d03b46815def9ce2db336ec0574ef11f5 100644 --- a/tests/reader/browser/test_reader_close_traffic.py +++ b/tests/reader/browser/test_reader_close_traffic.py @@ -72,7 +72,7 @@ class ReaderCloseTrafficTests(unittest.TestCase): return nativeFetch(url.pathname==='/api/reader-content'?location.origin+url.pathname+url.search:input,init); };''') page.goto(origin+'/static/manifest.json') - page.add_script_tag(url=origin+'/static/search/reader-navigation.js') + page.add_script_tag(url=origin+'/static/search/reader-host/application/navigation.js') page.evaluate('''url => { window.__navigation = VoiceOfMLReaderNavigation.createNavigation('/static/reader.html'); window.__reader = __navigation.mount(new URL(url)); diff --git a/tests/reader/browser/test_reader_navigation_host.py b/tests/reader/browser/test_reader_navigation_host.py index f0b250bfd630b466a670316e4735d56d71808a34..25403705a65dd3e9e317419f226a5d0c0fde2133 100644 --- a/tests/reader/browser/test_reader_navigation_host.py +++ b/tests/reader/browser/test_reader_navigation_host.py @@ -140,7 +140,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' const trigger=document.createElement('button');document.body.append(trigger);trigger.focus(); const existing=document.createElement('div');existing.setAttribute('inert',''); existing.setAttribute('aria-hidden','false');document.body.append(existing); - const readerPath=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html'); + const readerPath=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src).pathname.replace('search/reader-host/application/navigation.js','reader.html'); const target=readerPath+'?ext=txt&url=https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/a.txt'; const returnUrl=location.href; navigateToReader(target);const first=readerHost.overlay; @@ -196,7 +196,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' def test_reader_title_tracks_foreground_and_restores_search(self): result = self.page.evaluate('''async () => { document.title='搜索原始标题'; - const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html'); + const path=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src).pathname.replace('search/reader-host/application/navigation.js','reader.html'); const send=(source,title,origin=location.origin)=>window.dispatchEvent(new MessageEvent('message', {origin,source,data:{type:'voice-reader-title',title}})); navigateToReader(path+'?ext=txt'); const first=readerHost.overlay; @@ -647,7 +647,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' }; const holder=document.createElement('div');holder.id='priority-reader-test'; DOM.sidebarContent.parentNode.insertBefore(holder,DOM.sidebarContent); - const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html'); + const path=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src).pathname.replace('search/reader-host/application/navigation.js','reader.html'); for(const id of ['aaaaaaaaaaaaa','bbbbbbbbbbbbb']){ const row=document.createElement('div');row.className='browser-item';row.dataset.type='file'; row.dataset.readerUrl=path+'?id='+id+'&ext=txt';row.dataset.readUrl=row.dataset.readerUrl; @@ -694,7 +694,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' options.signal.addEventListener('abort',()=>reject(new DOMException('cancelled','AbortError')),{once:true}); }); }; - const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html'); + const path=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src).pathname.replace('search/reader-host/application/navigation.js','reader.html'); const first=document.createElement('button'),second=document.createElement('button'); first.dataset.readerUrl=path+'?id=aaaaaaaaaaaaa&ext=txt'; second.dataset.readerUrl=path+'?id=ccccccccccccc&ext=txt'; @@ -743,7 +743,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' Link:'https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/next.txt',Folder:[]}))); }; try { - const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html'); + const path=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src).pathname.replace('search/reader-host/application/navigation.js','reader.html'); navigateToReader(path+'?ext=txt');closeReaderOverlay();history.replaceState(null,'',previousUrl); await randomTxt();await new Promise(resolve=>originalTimer(resolve,100)); const recovered=aborted&&!!readerHost.overlay; @@ -893,7 +893,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' def test_untrusted_and_stale_messages_cannot_change_active_reader(self): result = self.page.evaluate('''() => { - const readerPath=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html'); + const readerPath=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src).pathname.replace('search/reader-host/application/navigation.js','reader.html'); const target=readerPath+'?ext=txt';navigateToReader(target); const first=readerHost.overlay, oldSource=first.contentWindow, theme=STATE.isDark; const message={type:'voice-reader-open',url:target+'&title=bad'}; @@ -910,7 +910,7 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' def test_unavailable_session_storage_does_not_block_replacement(self): result = self.page.evaluate('''() => { - const readerPath=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src).pathname.replace('search/reader-navigation.js','reader.html'); + const readerPath=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src).pathname.replace('search/reader-host/application/navigation.js','reader.html'); const target=readerPath+'?ext=txt';navigateToReader(target);const first=readerHost.overlay; const original=Storage.prototype.setItem; try { @@ -928,8 +928,8 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' return {url:location.href, state:history.state, rows:STATE.results.map(getResultStableId)}; }''') opened = self.page.evaluate('''() => { - const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src) - .pathname.replace('search/reader-navigation.js','reader.html'); + const path=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src) + .pathname.replace('search/reader-host/application/navigation.js','reader.html'); navigateToReader(path+'?ext=txt&title=Delayed'); history.replaceState({...history.state, foreignReader:{keep:2}}, '', location.href); return {url:location.href, state:history.state, length:history.length}; @@ -969,8 +969,8 @@ process.stdout.write(stripBundledScripts(readFileSync('static/index.html','utf8' def test_watchdog_recovery_rejects_foreign_and_non_search_targets(self): self.page.evaluate('''() => { - const path=new URL(document.querySelector('script[src*="search/reader-navigation.js"]').src) - .pathname.replace('search/reader-navigation.js','reader.html'); + const path=new URL(document.querySelector('script[src*="search/reader-host/application/navigation.js"]').src) + .pathname.replace('search/reader-host/application/navigation.js','reader.html'); navigateToReader(path+'?ext=txt'); }''') self.page.frame_locator('.reader-overlay').locator('body').wait_for() diff --git a/tests/reader/browser/test_reader_speech.py b/tests/reader/browser/test_reader_speech.py index 47f452f8509b9e7177a99b7b02158bf55ad0736a..3adf4b0bd4747a38a644a5085e044df90fadfdf6 100644 --- a/tests/reader/browser/test_reader_speech.py +++ b/tests/reader/browser/test_reader_speech.py @@ -153,10 +153,10 @@ class ReaderSpeechTest(unittest.TestCase): return context, page, posts, errors # A same-origin host page owning the Reader overlay through the shared navigation module. base = reader.split("reader.html")[0] - page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded") + page.goto(base + "search/reader-host/application/navigation.js", wait_until="domcontentloaded") # Inject as content: this host document has no charset, so a src= script would decode as Latin-1. page.add_style_tag(content=(ROOT / "static/style.css").read_text(encoding="utf-8")) - page.add_script_tag(content=(ROOT / "static/search/reader-navigation.js").read_text(encoding="utf-8")) + page.add_script_tag(content=(ROOT / "static/search/reader-host/application/navigation.js").read_text(encoding="utf-8")) page.evaluate("""url => { window.__nav = VoiceOfMLReaderNavigation.createNavigation(new URL(url).pathname, { resume: next => __nav.mount(new URL(next)) }); window.__reader = __nav.mount(new URL(url)); @@ -414,9 +414,9 @@ class ReaderSpeechTest(unittest.TestCase): before = len(posts) reader = page.url base = reader.split("reader.html")[0] - page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded") # leaving fires pagehide + page.goto(base + "search/reader-host/application/navigation.js", wait_until="domcontentloaded") # leaving fires pagehide page.add_style_tag(content=(ROOT / "static/style.css").read_text(encoding="utf-8")) - page.add_script_tag(content=(ROOT / "static/search/reader-navigation.js").read_text(encoding="utf-8")) + page.add_script_tag(content=(ROOT / "static/search/reader-host/application/navigation.js").read_text(encoding="utf-8")) page.evaluate("url => { window.__nav = VoiceOfMLReaderNavigation.createNavigation(new URL(url).pathname, { resume: next => __nav.mount(new URL(next)) }); }", reader) bar = page.locator(".reader-speech-mini") bar.wait_for(timeout=5000) @@ -434,7 +434,7 @@ class ReaderSpeechTest(unittest.TestCase): frame.locator("#speech-stop").click() page.goto(reader, wait_until="domcontentloaded") wait(page, "() => document.documentElement.dataset.readerPhase === 'ready'", 30000) - page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded") + page.goto(base + "search/reader-host/application/navigation.js", wait_until="domcontentloaded") self.assertEqual(page.evaluate("() => sessionStorage.getItem('reader-speech-handoff')"), None) self.assertFalse(errors, errors) finally: @@ -451,9 +451,9 @@ class ReaderSpeechTest(unittest.TestCase): base = reader.split("reader.html")[0] page.goto(base + "empty", wait_until="domcontentloaded") # pagehide writes the handoff page.evaluate("() => sessionStorage.removeItem('reader-speech-handoff')") - page.goto(base + "search/reader-navigation.js", wait_until="domcontentloaded") + page.goto(base + "search/reader-host/application/navigation.js", wait_until="domcontentloaded") page.add_style_tag(content=(ROOT / "static/style.css").read_text(encoding="utf-8")) - page.add_script_tag(content=(ROOT / "static/search/reader-navigation.js").read_text(encoding="utf-8")) + page.add_script_tag(content=(ROOT / "static/search/reader-host/application/navigation.js").read_text(encoding="utf-8")) page.evaluate("url => { window.__nav = VoiceOfMLReaderNavigation.createNavigation(new URL(url).pathname, { resume: next => __nav.mount(new URL(next)) }); }", reader) bar = page.locator(".reader-speech-mini") bar.wait_for(timeout=5000) diff --git a/tests/search/baselines/test_search_extension_filter_baseline.mjs b/tests/search/baselines/test_search_extension_filter_baseline.mjs index 8c2d239d2e4a1b13f1c75c8cb7fcaae2ea5929c1..33c3deec72044fc6cfbb660727702277c842a325 100644 --- a/tests/search/baselines/test_search_extension_filter_baseline.mjs +++ b/tests/search/baselines/test_search_extension_filter_baseline.mjs @@ -20,7 +20,7 @@ function fixture(data, selected = []) { renderExtensionTree(_container, items, rest, selection, callback) { c.capture = {items: local(items), rest: local(rest), selected: local(selection), callback}; }}); - const filename = path.join(process.cwd(), 'static/search/file-types.js'); + const filename = path.join(process.cwd(), 'static/search/catalog/domain/file-types.js'); vm.runInContext(fs.readFileSync(filename, 'utf8'), c, {filename}); const controllerFile = path.join(process.cwd(), 'static/search/sidebar/application/filters.js'); vm.runInContext(fs.readFileSync(controllerFile, 'utf8'), c, {filename: controllerFile}); diff --git a/tests/search/baselines/test_search_extension_inventory_baseline.mjs b/tests/search/baselines/test_search_extension_inventory_baseline.mjs index b26c7fc46a88f4c28cc7d8f17e6947611f0479b4..efdc0f2f24a47beea6eaf10fe5e9584295963c30 100644 --- a/tests/search/baselines/test_search_extension_inventory_baseline.mjs +++ b/tests/search/baselines/test_search_extension_inventory_baseline.mjs @@ -6,7 +6,7 @@ import test from 'node:test'; import vm from 'node:vm'; const context = vm.createContext({}); -const filename = path.join(process.cwd(), 'static/search/file-types.js'); +const filename = path.join(process.cwd(), 'static/search/catalog/domain/file-types.js'); vm.runInContext(fs.readFileSync(filename, 'utf8'), context, {filename}); const host = fs.readFileSync(path.join(process.cwd(), 'static/app.js'), 'utf8'); for (const pattern of [/^const ORDERED_EXTENSIONS = [^\n]+/m, /^const FILE_ICON_MAP = [^\n]+/m, diff --git a/tests/search/baselines/test_search_folder_selection_baseline.mjs b/tests/search/baselines/test_search_folder_selection_baseline.mjs index 9815516dc59bc24cd4de922bd6681090d66f4227..ce39f27de199aeff8a3547c171795a5c9a5dbef8 100644 --- a/tests/search/baselines/test_search_folder_selection_baseline.mjs +++ b/tests/search/baselines/test_search_folder_selection_baseline.mjs @@ -6,7 +6,7 @@ import test from 'node:test'; import vm from 'node:vm'; const root = process.cwd(); -const modulePath = path.join(root, 'static/search/folder-selection.js'); +const modulePath = path.join(root, 'static/search/sidebar/domain/folder-selection.js'); const context = vm.createContext({}); vm.runInContext(fs.readFileSync(modulePath, 'utf8'), context, {filename: modulePath}); const api = context.VoiceOfMLSearchFolderSelection; diff --git a/tests/search/baselines/test_search_response_validation_baseline.mjs b/tests/search/baselines/test_search_response_validation_baseline.mjs index b866634396f2433de3b9bdf422039b2c6ef534d5..3bac766d22a5d72081605ea9d3b1ad5f74255835 100644 --- a/tests/search/baselines/test_search_response_validation_baseline.mjs +++ b/tests/search/baselines/test_search_response_validation_baseline.mjs @@ -10,7 +10,7 @@ const source = fs.readFileSync(path.join(root, 'static/app.js'), 'utf8'); const match = source.match(/^function isValidSearchResponse\([^]*?^}/m); assert.ok(match, 'host validator binding must remain inline'); const context = vm.createContext({}); -const filename = path.join(root, 'static/search/response-validation.js'); +const filename = path.join(root, 'static/search/requests/domain/response-validation.js'); vm.runInContext(fs.readFileSync(filename, 'utf8'), context, {filename}); vm.runInContext(match[0], context); const validate = context.isValidSearchResponse; diff --git a/tests/search/baselines/test_search_stable_id_baseline.mjs b/tests/search/baselines/test_search_stable_id_baseline.mjs index eed8cbf4717f0f4333571d6971056c47071b2343..03e47666e9f6fdb610cc6995faaf64119133e8d7 100644 --- a/tests/search/baselines/test_search_stable_id_baseline.mjs +++ b/tests/search/baselines/test_search_stable_id_baseline.mjs @@ -7,9 +7,9 @@ import vm from 'node:vm'; const root = process.cwd(); const context = vm.createContext({}); -const dependency = path.join(root, 'static/search/record-path.js'); +const dependency = path.join(root, 'static/search/catalog/domain/record-path.js'); vm.runInContext(fs.readFileSync(dependency, 'utf8'), context, {filename: dependency}); -const identity = path.join(root, 'static/search/result-identity.js'); +const identity = path.join(root, 'static/search/results/domain/result-identity.js'); vm.runInContext(fs.readFileSync(identity, 'utf8'), context, {filename: identity}); const source = fs.readFileSync(path.join(root, 'static/app.js'), 'utf8'); const match = source.match(/^function getResultStableId\([^]*?^}/m); diff --git a/tests/search/browser/test_search_session_browser.py b/tests/search/browser/test_search_session_browser.py index 994afbfc505bb35c0c22a94a12c467ed5e76f640..7d69e66a3f7c6391450d3210242aa98019601ecd 100644 --- a/tests/search/browser/test_search_session_browser.py +++ b/tests/search/browser/test_search_session_browser.py @@ -12,7 +12,7 @@ class SearchSessionBrowserTests(unittest.TestCase): self.page.route("**/search-session-fixture*", lambda route: route.fulfill( status=200, content_type="text/html", body="Session")) self.page.goto(self.origin + "/search-session-fixture?q=first") - self.page.add_script_tag(url=self.origin + support.PREFIX + "/static/search/search-session.js") + self.page.add_script_tag(url=self.origin + support.PREFIX + "/static/search/execution/application/session.js") def test_session_persist_and_restore_with_real_indexeddb(self): self.open_session_fixture() diff --git a/tests/search/browser/test_session_transaction_browser.py b/tests/search/browser/test_session_transaction_browser.py index 3d0cf9d55b5e5d12f72e94628f778b6541bfdaa3..af1e2f3d455386960f6ae240cf11f1b98ac1f33e 100644 --- a/tests/search/browser/test_session_transaction_browser.py +++ b/tests/search/browser/test_session_transaction_browser.py @@ -49,7 +49,7 @@ class SessionTransactionBrowserTests(unittest.TestCase): self.page.route('**/session-fixture*', lambda route: route.fulfill( content_type='text/html', body='Session transaction')) self.page.goto(self.origin + '/session-fixture?q=first') - self.page.add_script_tag(url=self.origin + '/static/search/search-session.js') + self.page.add_script_tag(url=self.origin + '/static/search/execution/application/session.js') self.page.evaluate('''() => { window.session = VoiceOfMLSearchSession.createSearchSession({ canPersist: () => true, canRestore: target => !target || target.origin === location.origin diff --git a/tests/search/build/test_search_record_path_build.mjs b/tests/search/build/test_search_record_path_build.mjs index 458406f937f854dd731f45014a1042aa64160cca..a2040d2e966659541801714e315ed038b9a3a073 100644 --- a/tests/search/build/test_search_record_path_build.mjs +++ b/tests/search/build/test_search_record_path_build.mjs @@ -6,13 +6,13 @@ import {APP_DEPENDENCIES, stripBundledScripts} from "../../../scripts/build/comp const resources = createRequire(import.meta.url)("../../../static/reader-resources.js"); const html = readFileSync("static/index.html", "utf8"); const worker = readFileSync("static/sw.js", "utf8"); -const moduleName = "search/record-path.js"; -const highlightName = "search/highlight.js"; -const cacheName = "search/response-cache.js"; -const typesName = "search/file-types.js"; -const validationName = "search/response-validation.js"; -const identityName = "search/result-identity.js"; -const folderSelectionName = "search/folder-selection.js"; +const moduleName = "search/catalog/domain/record-path.js"; +const highlightName = "search/results/presentation/highlight.js"; +const cacheName = "search/requests/infrastructure/response-cache.js"; +const typesName = "search/catalog/domain/file-types.js"; +const validationName = "search/requests/domain/response-validation.js"; +const identityName = "search/results/domain/result-identity.js"; +const folderSelectionName = "search/sidebar/domain/folder-selection.js"; const heightIndexName = "search/domain/height-index.js"; const canonicalName = "search/domain/stable-stringify.js"; const viewKeyName = "search/domain/search-view-key.js"; @@ -20,31 +20,31 @@ const recoveryName = "search/domain/search-recovery.js"; const windowPageName = "search/domain/search-window-page.js"; const sidebarName = "search/presentation/sidebar-render.js"; assert.equal(APP_DEPENDENCIES.filter(name => name === moduleName).length, 1); -assert.equal((html.match(/

Search

`, + "index.html": `

Search

`, }), baseline, "hash the final HTML after bundled scripts are removed"); for (const invalid of [worker.replace("CACHE_VERSION = 'development'", "OTHER_VERSION = 'development'"), worker.replace("'development'", "'stale'"), worker + "const CACHE_VERSION = 'development';"]) { diff --git a/tests/search/download/test_download_controller_contract.js b/tests/search/download/test_download_controller_contract.js index b088929ddea7f4eaa93a6650a0e4b9697fcaa8a4..f93948f1545f97438143f98ff9a049234026c354 100644 --- a/tests/search/download/test_download_controller_contract.js +++ b/tests/search/download/test_download_controller_contract.js @@ -22,7 +22,7 @@ function fixture(overrides = {}) { return new Promise((resolve, reject) => requests.push({url, signal: options.signal, resolve, reject})); }, }; - const filename = path.join(__dirname, "../../../static/search/download-controller.js"); + const filename = path.join(__dirname, "../../../static/search/downloads/application/controller.js"); vm.runInNewContext(fs.readFileSync(filename, "utf8"), sandbox, {filename}); const controller = sandbox.VoiceOfMLDownloadController.createDownloadController({ buildCheckUrl: link => "check:" + link, diff --git a/tests/search/highlight/test_search_highlight_contract.js b/tests/search/highlight/test_search_highlight_contract.js index 97655efca41e2762b1f359315b75b7a379177294..0c8a6393210bf15908ebdb3a90e1f934d3022162 100644 --- a/tests/search/highlight/test_search_highlight_contract.js +++ b/tests/search/highlight/test_search_highlight_contract.js @@ -7,7 +7,7 @@ const vm = require("node:vm"); // Expectations were pinned against the original app.js before extraction. function extractedFunctions() { const context = vm.createContext({}); - const filename = path.join(__dirname, "../../../static/search/highlight.js"); + const filename = path.join(__dirname, "../../../static/search/results/presentation/highlight.js"); vm.runInContext(fs.readFileSync(filename, "utf8"), context, {filename}); return {context, escapeHTML: context.escapeHTML, highlightText: context.highlightText, getHighlightRegex: context.getHighlightRegex}; diff --git a/tests/search/reader-navigation/host_contracts.mjs b/tests/search/reader-navigation/host_contracts.mjs index 47a3105d2fbe3ea630887d402326ab1e52a9a978..7a3b28785adf5a43a46ee342655cd722dcc51ade 100644 --- a/tests/search/reader-navigation/host_contracts.mjs +++ b/tests/search/reader-navigation/host_contracts.mjs @@ -15,8 +15,8 @@ test('reader host dependencies are composed, cached and loaded before the app', const html = fs.readFileSync('static/index.html', 'utf8'), c = context(); vm.runInContext(fs.readFileSync('static/reader-resources.js', 'utf8'), c); for (const path of paths) { - assert.ok(APP_DEPENDENCIES.indexOf(path) > APP_DEPENDENCIES.indexOf('search/reader-navigation.js')); - assert.ok(html.indexOf(path) > html.indexOf('search/reader-navigation.js')); + assert.ok(APP_DEPENDENCIES.indexOf(path) > APP_DEPENDENCIES.indexOf('search/reader-host/application/navigation.js')); + assert.ok(html.indexOf(path) > html.indexOf('search/reader-host/application/navigation.js')); assert.ok(html.indexOf(path) < html.indexOf('static/app.js')); assert.ok(!stripBundledScripts(html).includes(path)); assert.ok(fs.readFileSync('static/sw.js', 'utf8').includes('/static/' + path)); diff --git a/tests/search/reader-navigation/test_reader_navigation_baseline.mjs b/tests/search/reader-navigation/test_reader_navigation_baseline.mjs index 0b6f4debc308ee234de7684d3caba5ead9abbb78..028f674537ea82048f774409909a241cfb773dc3 100644 --- a/tests/search/reader-navigation/test_reader_navigation_baseline.mjs +++ b/tests/search/reader-navigation/test_reader_navigation_baseline.mjs @@ -7,7 +7,7 @@ import path from 'node:path'; import test from 'node:test'; import vm from 'node:vm'; -const filename = path.join(process.cwd(), 'static/search/reader-navigation.js'); +const filename = path.join(process.cwd(), 'static/search/reader-host/application/navigation.js'); const source = fs.readFileSync(filename, 'utf8'); const origin = 'https://search.example'; const readerPath = '/search/static/reader.html'; diff --git a/tests/search/record-path/test_search_record_path.js b/tests/search/record-path/test_search_record_path.js index 65761f68ea025a546bf4a9fc80678d67e8378876..afdb0dee041134da9c429dec6df3f46d103c4795 100644 --- a/tests/search/record-path/test_search_record_path.js +++ b/tests/search/record-path/test_search_record_path.js @@ -6,7 +6,7 @@ const vm = require("node:vm"); // Expectations were captured from each site's original app.js functions. const app = fs.readFileSync(path.join(__dirname, "../../../static/app.js"), "utf8"); const sandbox = vm.createContext({}); -const filename = path.join(__dirname, "../../../static/search/record-path.js"); +const filename = path.join(__dirname, "../../../static/search/catalog/domain/record-path.js"); vm.runInContext(fs.readFileSync(filename, "utf8"), sandbox, {filename}); for (const name of ["getRecordLink", "getRecordPath", "getBrowserFileName", "getBrowserFileLink"]) { const match = app.match(new RegExp(`^function ${name}\\([^]*?^}`, "m")); diff --git a/tests/search/response-cache/test_search_response_cache_contract.js b/tests/search/response-cache/test_search_response_cache_contract.js index ee24d1ebba43694c5929294b7747585a18e6dadf..3a02d6c829ba062a3ce7ca5ef81b6217570524f5 100644 --- a/tests/search/response-cache/test_search_response_cache_contract.js +++ b/tests/search/response-cache/test_search_response_cache_contract.js @@ -7,7 +7,7 @@ const vm = require("node:vm"); // Expectations were pinned against each site's original cache before extraction. function fixture(limit = 3, ttl = 100, budget = 100) { const context = vm.createContext({clock: 0, limit, ttl, budget}); - const filename = path.join(__dirname, "../../../static/search/response-cache.js"); + const filename = path.join(__dirname, "../../../static/search/requests/infrastructure/response-cache.js"); vm.runInContext(fs.readFileSync(filename, "utf8"), context, {filename}); vm.runInContext(`Date.now = () => clock; globalThis.cache = new BoundedResponseCache(limit, ttl, budget);`, context); diff --git a/tests/search/session/test_positions_persistence.mjs b/tests/search/session/test_positions_persistence.mjs index f341f238597f7824eeb43712f754f72ab908364e..e6864da830dcfa274e23887555b88c16dcc08442 100644 --- a/tests/search/session/test_positions_persistence.mjs +++ b/tests/search/session/test_positions_persistence.mjs @@ -25,7 +25,7 @@ test('positions modules are composed once and synchronized across shell, resourc function fixture(overrides = {}) { const context = vm.createContext({indexedDB, IDBKeyRange, setTimeout, clearTimeout, TextEncoder, AbortController, ...overrides}); - for (const file of ['search-session.js', 'domain/search-window-page.js', + for (const file of ['execution/application/session.js', 'domain/search-window-page.js', 'positions/domain/policy.js', 'positions/infrastructure/indexed-db.js', 'positions/application/persistence.js']) { vm.runInContext(readFileSync(new URL('../../../static/search/' + file, import.meta.url), 'utf8'), context); } diff --git a/tests/search/session/test_search_session_contract.js b/tests/search/session/test_search_session_contract.js index e959e0ac883b04a9d011a1bc4b158275847fb69f..1b09f634addaaf00e24adae1b76252ad3b4b4d41 100644 --- a/tests/search/session/test_search_session_contract.js +++ b/tests/search/session/test_search_session_contract.js @@ -5,7 +5,7 @@ const test = require('node:test'); const vm = require('node:vm'); const {IDBFactory} = require('fake-indexeddb'); -const filename = path.join(__dirname, '../../../static/search/search-session.js'); +const filename = path.join(__dirname, '../../../static/search/execution/application/session.js'); const source = fs.readFileSync(filename, 'utf8'); const turn = () => new Promise(resolve => setImmediate(resolve)); async function until(predicate) { diff --git a/tests/search/size/test_search_size_format.js b/tests/search/size/test_search_size_format.js index 181136b102c5b0883a79d92fd29a20dc206001e7..647e041c3e2ee7c7bde7cb014d8481d3437685d8 100644 --- a/tests/search/size/test_search_size_format.js +++ b/tests/search/size/test_search_size_format.js @@ -5,7 +5,7 @@ const vm = require("node:vm"); // The expectations were captured from the original functions in app.js. const sandbox = vm.createContext({}); -const filename = path.join(__dirname, "../../../static/search/size-format.js"); +const filename = path.join(__dirname, "../../../static/search/results/presentation/size-format.js"); vm.runInContext(fs.readFileSync(filename, "utf8"), sandbox, {filename}); const {bytesToDisplay, fmtSizeUrl, parseSizeStr} = sandbox; for (const [input, value, unit] of [ diff --git a/tests/search/size/test_search_size_render_contract.js b/tests/search/size/test_search_size_render_contract.js index 5a71205f48571aa192f5dc07638c16d348331620..5f3ecd239bafbb7a630784ea7e5e9da7b44be3b7 100644 --- a/tests/search/size/test_search_size_render_contract.js +++ b/tests/search/size/test_search_size_render_contract.js @@ -7,7 +7,7 @@ const vm = require("node:vm"); // Expected behavior was pinned before extraction, separately from URL sizes. function extractedFormatter() { const context = vm.createContext({}); - const filename = path.join(__dirname, "../../../static/search/size-format.js"); + const filename = path.join(__dirname, "../../../static/search/results/presentation/size-format.js"); vm.runInContext(fs.readFileSync(filename, "utf8"), context, {filename}); return context.formatSize; } @@ -53,7 +53,7 @@ test("display retains prototype and normalized cache behavior", () => { assert.equal(numericInfinityFirst("Infinity"), "Infinity GB"); // The legacy cache deliberately reads a value twice after the undefined check. const context = vm.createContext({}); - const filename = path.join(__dirname, "../../../static/search/size-format.js"); + const filename = path.join(__dirname, "../../../static/search/results/presentation/size-format.js"); vm.runInContext(fs.readFileSync(filename, "utf8"), context, {filename}); const observed = vm.runInContext(`(() => { let reads = 0; diff --git a/tests/search/ui/catalog_contracts.mjs b/tests/search/ui/catalog_contracts.mjs index 02689b85fd5cd4242b24ee4ae5939ea2fb758d32..f31b72cb692eb356a2a284cd193962dde5850fb4 100644 --- a/tests/search/ui/catalog_contracts.mjs +++ b/tests/search/ui/catalog_contracts.mjs @@ -22,7 +22,7 @@ function fixture(baseline = false) { return new Promise(resolve => workers.push({type, payload, timeout, resolve})); }, }); - vm.runInContext(fs.readFileSync('static/search/response-cache.js', 'utf8'), c); + vm.runInContext(fs.readFileSync('static/search/requests/infrastructure/response-cache.js', 'utf8'), c); vm.runInContext('Date.now = () => clock', c); const old = baseline && fs.readFileSync(process.env.CATALOG_BASELINE_ROOT + '/static/app.js', 'utf8'); const source = old || app; diff --git a/tests/search/ui/test_folder_selection.js b/tests/search/ui/test_folder_selection.js index bdae316a24ce80ab5043e28d0ebc551d514518ea..5512486660502e20d8a6323626c8d0959691bac1 100644 --- a/tests/search/ui/test_folder_selection.js +++ b/tests/search/ui/test_folder_selection.js @@ -4,10 +4,10 @@ const path = require('path'); const vm = require('vm'); // Exercise the DOM-facing selection projection against actual file membership. -// The pure projection lives in static/search/folder-selection.js; the host keeps +// The pure projection lives in static/search/sidebar/domain/folder-selection.js; the host keeps // the memo, branch splitting and normalization that call it through the namespace. const source = fs.readFileSync(path.join(__dirname, '../../../static/app.js'), 'utf8'); -const moduleSource = fs.readFileSync(path.join(__dirname, '../../../static/search/folder-selection.js'), 'utf8'); +const moduleSource = fs.readFileSync(path.join(__dirname, '../../../static/search/sidebar/domain/folder-selection.js'), 'utf8'); const context = vm.createContext({Set, STATE: {folderTree: []}}); vm.runInContext(moduleSource, context); assert.strictEqual(source.indexOf('function folderPathCovered('), -1); diff --git a/tests/seo/test_seo_routes.py b/tests/seo/test_seo_routes.py index 1e413a09374348bdabe7e8dde824233f741570c8..ad6506a6df3601db277fe4ddf8f28410319ffc19 100644 --- a/tests/seo/test_seo_routes.py +++ b/tests/seo/test_seo_routes.py @@ -107,7 +107,8 @@ class SeoBuildSafetyTests(unittest.TestCase): rows.append([repos.index(repo), stem, extension, folders.index(folder), 1, 0]) payload = {"v": 2, "rp": repos, "fd": folders, "rc": rows} expected = seo.build_catalog(seo.decode_corpus(payload), project="hf", corpus_identity="unused") - with TemporaryDirectory() as directory: + for module in ('backend.seo', 'backend.site.application.seo'): + with self.subTest(module=module), TemporaryDirectory() as directory: root = Path(directory) corpus = root / "corpus.json.gz" corpus.write_bytes(gzip.compress(json.dumps(payload).encode())) @@ -115,8 +116,8 @@ class SeoBuildSafetyTests(unittest.TestCase): args = ["seo.py", "--project", "hf", "--corpus", str(corpus), "--output", str(output)] with patch.object(sys, "argv", args), patch("builtins.print") as printed, \ patch.dict(sys.modules), self.assertRaises(SystemExit) as exited: - sys.modules.pop("backend.seo", None) - runpy.run_module("backend.seo", run_name="__main__") + sys.modules.pop(module, None) + runpy.run_module(module, run_name="__main__") self.assertEqual(exited.exception.code, 0) summary = json.loads(printed.call_args.args[0]) self.assertEqual(summary, {key: expected["manifest"][key] for key in ("project", "record_count", "detail_count", "folder_count")}) diff --git a/tests/support/classic_search_modules.js b/tests/support/classic_search_modules.js index fb0f0bcb60be88b30fe9facb602872a7b8c45ff9..5ef274e8eb7e427e5dd8b5f15fa3034100a37c74 100644 --- a/tests/support/classic_search_modules.js +++ b/tests/support/classic_search_modules.js @@ -5,7 +5,7 @@ const fs = require("fs"); const path = require("path"); const vm = require("vm"); -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", +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/execution/application/session.js", "static/search/domain/search-window-page.js", "static/search/positions/domain/policy.js", "static/search/positions/infrastructure/indexed-db.js", "static/search/positions/application/persistence.js", "static/search/positions/application/restoration.js", "static/search/results/presentation/row.js", "static/search/results/application/interactions.js", "static/search/discovery/application/random.js", @@ -17,9 +17,9 @@ const MODULES = ["static/search/execution/domain/policy.js", "static/search/exec "static/search/history/infrastructure/store.js", "static/search/history/application/controller.js", "static/search/ambient/application/quotation.js", "static/search/results/snapshots/domain/copy-budget.js", "static/search/results/snapshots/application/store.js", - "static/search/folder-selection.js", "static/search/domain/height-index.js", + "static/search/sidebar/domain/folder-selection.js", "static/search/domain/height-index.js", "static/search/reader-host/presentation/return-position.js", "static/search/reader-host/application/host.js", - "static/search/response-cache.js", "static/search/requests/application/response-store.js", + "static/search/requests/infrastructure/response-cache.js", "static/search/requests/application/response-store.js", "static/search/catalog/domain/sidebar-payload.js", "static/search/catalog/application/client.js", "static/search/requests/infrastructure/shared-transport.js", "static/search/requests/application/prefetch-controller.js", "static/search/results/window/application/page-loader.js", "static/search/results/window/presentation/status.js"]; diff --git a/tests/support/coverage_history.py b/tests/support/coverage_history.py index 1b0a512434e4a275a79a82c9fdc39f038cb13b73..b942a67f01f8bc598ca2e7d85ad0b952296b9619 100644 --- a/tests/support/coverage_history.py +++ b/tests/support/coverage_history.py @@ -15,6 +15,12 @@ def build_coverage_history(root: Path, destination: Path) -> Path: shutil.copytree(root / name, destination / name, ignore=shutil.ignore_patterns('__pycache__', '*.pyc')) for name in ('app.py', 'pyrightconfig.json', 'pyrightconfig.strict.json'): shutil.copyfile(root / name, destination / name) + from scripts.backend_paths import MAP_FILE, migration, reviewed_source, validate_migration + if (root / MAP_FILE).is_file(): + validate_migration(root) + for name in migration(root)['sources']: + (destination / name).write_bytes(reviewed_source(root, name)) + (destination / MAP_FILE).unlink() anchors = destination / 'scripts/coverage-anchors' shutil.copyfile(anchors / 'transport-parent-app.py.snapshot', destination / 'backend/app.py') shutil.copyfile(anchors / 'proxy-safety-new-streams.py.snapshot', destination / 'backend/proxy_streams.py') diff --git a/tests/support/sidebar_fixture.js b/tests/support/sidebar_fixture.js index 530c1b8257fa0109015e0c731469fc469bd1403e..f98c860b9cb344ce6a5baa73e02f132d59c81404 100644 --- a/tests/support/sidebar_fixture.js +++ b/tests/support/sidebar_fixture.js @@ -5,7 +5,7 @@ const vm = require('vm'); // Load the actual feature; expose private selection operations only in this VM // so the exhaustive membership tests retain their original coverage. function installSidebarTree(root, context) { - vm.runInContext(fs.readFileSync(path.join(root, 'static/search/folder-selection.js'), 'utf8'), context); + vm.runInContext(fs.readFileSync(path.join(root, 'static/search/sidebar/domain/folder-selection.js'), 'utf8'), context); let source = fs.readFileSync(path.join(root, 'static/search/sidebar/presentation/folder-tree.js'), 'utf8'); source = source.replace('return { render: renderFilterFolderTree,', 'return { normalizeFolderSelection, setNodeSubtreeSelection, splitFolderSelection, getFolderSelfSet, render: renderFilterFolderTree,');