Spaces:
Running
Running
Upload 6 files
Browse files- app/bucket_snapshot.py +58 -9
- app/data_loader.py +50 -14
- app/doc_store.py +1 -0
- app/facet_store.py +1 -0
- app/indexer.py +28 -8
- app/main.py +102 -6
app/bucket_snapshot.py
CHANGED
|
@@ -53,14 +53,17 @@ def snapshot_status() -> dict[str, Any] | None:
|
|
| 53 |
return None
|
| 54 |
|
| 55 |
def publish_due(bucket_dir: Path, minimum_interval_seconds: int) -> bool:
|
|
|
|
|
|
|
|
|
|
| 56 |
if minimum_interval_seconds <= 0:
|
| 57 |
-
return
|
| 58 |
try:
|
| 59 |
manifest = json.loads(manifest_path(bucket_dir).read_text(encoding="utf-8"))
|
| 60 |
created_at = int(manifest.get("created_at", 0))
|
| 61 |
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
| 62 |
-
return
|
| 63 |
-
return time.time() - created_at
|
| 64 |
|
| 65 |
|
| 66 |
def local_repository() -> Path:
|
|
@@ -75,6 +78,12 @@ def clear_directory(path: Path) -> None:
|
|
| 75 |
else:
|
| 76 |
child.unlink()
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
def sha256(path: Path) -> str:
|
| 80 |
digest = hashlib.sha256()
|
|
@@ -184,8 +193,40 @@ def copy_validated(source: Path, destination: Path, metadata: dict[str, Any], at
|
|
| 184 |
|
| 185 |
|
| 186 |
def publish(bucket_dir: Path) -> None:
|
| 187 |
-
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
def _publish(bucket_dir: Path) -> None:
|
| 191 |
if not bucket_dir.is_dir():
|
|
@@ -218,7 +259,7 @@ def _publish(bucket_dir: Path) -> None:
|
|
| 218 |
write_snapshot_status("publishing", stage="copy_generation", snapshot=snapshot)
|
| 219 |
generation_dir = bucket_dir / GENERATIONS_ROOT / generation
|
| 220 |
generation_dir.mkdir(parents=True, exist_ok=False)
|
| 221 |
-
shutil.copytree(local_repository(), generation_dir / REPOSITORY_DIRNAME)
|
| 222 |
sidecars: dict[str, dict[str, Any]] = {}
|
| 223 |
with tempfile.TemporaryDirectory(dir=DATA_ROOT, prefix="bha-snapshot-") as temporary_dir:
|
| 224 |
for key, source in SIDECARS.items():
|
|
@@ -252,7 +293,10 @@ def _publish(bucket_dir: Path) -> None:
|
|
| 252 |
shutil.rmtree(legacy_repository)
|
| 253 |
except Exception as exc:
|
| 254 |
print(f"bha_bucket_snapshot=cleanup_failed error={type(exc).__name__}", flush=True)
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
| 256 |
print(f"bha_bucket_snapshot=published snapshot={snapshot} elapsed_seconds={time.monotonic() - started:.2f}", flush=True)
|
| 257 |
|
| 258 |
|
|
@@ -260,6 +304,7 @@ def restore_sidecars(bucket_dir: Path, manifest: dict[str, Any]) -> None:
|
|
| 260 |
generation_dir = bucket_dir / GENERATIONS_ROOT / str(manifest["generation"])
|
| 261 |
DATA_ROOT.mkdir(parents=True, exist_ok=True)
|
| 262 |
temporary_paths: list[tuple[Path, Path]] = []
|
|
|
|
| 263 |
try:
|
| 264 |
for key, target in SIDECARS.items():
|
| 265 |
metadata = manifest["sidecars"][key]
|
|
@@ -282,8 +327,9 @@ def restore_sidecars(bucket_dir: Path, manifest: dict[str, Any]) -> None:
|
|
| 282 |
Path(f"{target}-shm").unlink(missing_ok=True)
|
| 283 |
for temporary, target in temporary_paths:
|
| 284 |
os.replace(temporary, target)
|
|
|
|
| 285 |
except Exception:
|
| 286 |
-
for
|
| 287 |
target.unlink(missing_ok=True)
|
| 288 |
for backup, target in backups:
|
| 289 |
os.replace(backup, target)
|
|
@@ -332,6 +378,7 @@ def restore(bucket_dir: Path, allow_stale: bool = True) -> bool:
|
|
| 332 |
write_snapshot_status("unavailable", stage="read_manifest", reason="missing_or_invalid_manifest")
|
| 333 |
print("bha_bucket_snapshot=unavailable reason=missing_or_invalid_manifest", flush=True)
|
| 334 |
return False
|
|
|
|
| 335 |
try:
|
| 336 |
remote_commits = {str(key): value for key, value in parsed_archive_commits(remote=True).items()}
|
| 337 |
if manifest["archive_commits"] != remote_commits:
|
|
@@ -339,10 +386,12 @@ def restore(bucket_dir: Path, allow_stale: bool = True) -> bool:
|
|
| 339 |
write_snapshot_status("unavailable", stage="validate_source", reason="source_fingerprint_mismatch")
|
| 340 |
print("bha_bucket_snapshot=unavailable reason=source_fingerprint_mismatch", flush=True)
|
| 341 |
return False
|
|
|
|
| 342 |
write_snapshot_status("stale_source", stage="validate_source", reason="source_fingerprint_mismatch")
|
| 343 |
print("bha_bucket_snapshot=stale_source reason=source_fingerprint_mismatch", flush=True)
|
| 344 |
except Exception as exc:
|
| 345 |
if allow_stale:
|
|
|
|
| 346 |
write_snapshot_status("source_fingerprint_unverified", stage="validate_source", reason=type(exc).__name__)
|
| 347 |
print(f"bha_bucket_snapshot=source_fingerprint_unverified reason={type(exc).__name__}", flush=True)
|
| 348 |
else:
|
|
@@ -414,7 +463,7 @@ def restore(bucket_dir: Path, allow_stale: bool = True) -> bool:
|
|
| 414 |
clear_directory(local_repository())
|
| 415 |
write_snapshot_status(
|
| 416 |
"restored", stage="complete", snapshot=str(manifest["snapshot"]),
|
| 417 |
-
elapsed_seconds=round(time.monotonic() - started, 2),
|
| 418 |
)
|
| 419 |
print(f"bha_bucket_snapshot=restored snapshot={manifest['snapshot']} elapsed_seconds={time.monotonic() - started:.2f}", flush=True)
|
| 420 |
return True
|
|
|
|
| 53 |
return None
|
| 54 |
|
| 55 |
def publish_due(bucket_dir: Path, minimum_interval_seconds: int) -> bool:
|
| 56 |
+
return publish_delay(bucket_dir, minimum_interval_seconds) <= 0
|
| 57 |
+
|
| 58 |
+
def publish_delay(bucket_dir: Path, minimum_interval_seconds: int) -> int:
|
| 59 |
if minimum_interval_seconds <= 0:
|
| 60 |
+
return 0
|
| 61 |
try:
|
| 62 |
manifest = json.loads(manifest_path(bucket_dir).read_text(encoding="utf-8"))
|
| 63 |
created_at = int(manifest.get("created_at", 0))
|
| 64 |
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
| 65 |
+
return 0
|
| 66 |
+
return max(0, int(minimum_interval_seconds - (time.time() - created_at)))
|
| 67 |
|
| 68 |
|
| 69 |
def local_repository() -> Path:
|
|
|
|
| 78 |
else:
|
| 79 |
child.unlink()
|
| 80 |
|
| 81 |
+
def link_or_copy(source: str | os.PathLike[str], destination: str | os.PathLike[str]) -> None:
|
| 82 |
+
try:
|
| 83 |
+
os.link(source, destination)
|
| 84 |
+
except OSError:
|
| 85 |
+
shutil.copy2(source, destination)
|
| 86 |
+
|
| 87 |
|
| 88 |
def sha256(path: Path) -> str:
|
| 89 |
digest = hashlib.sha256()
|
|
|
|
| 193 |
|
| 194 |
|
| 195 |
def publish(bucket_dir: Path) -> None:
|
| 196 |
+
# Readers can continue while publication snapshots one stable generation;
|
| 197 |
+
# generation activation takes the exclusive lock and waits for this copy.
|
| 198 |
+
try:
|
| 199 |
+
with serving_lock():
|
| 200 |
+
_publish(bucket_dir)
|
| 201 |
+
except Exception as exc:
|
| 202 |
+
cleanup_failed_publication(bucket_dir)
|
| 203 |
+
detail = str(exc).replace("\n", " ")[:500]
|
| 204 |
+
write_snapshot_status("publish_failed", stage="publish", reason=type(exc).__name__, detail=detail)
|
| 205 |
+
raise
|
| 206 |
+
|
| 207 |
+
def cleanup_failed_publication(bucket_dir: Path) -> None:
|
| 208 |
+
keep_generation: str | None = None
|
| 209 |
+
try:
|
| 210 |
+
raw = json.loads(manifest_path(bucket_dir).read_text(encoding="utf-8"))
|
| 211 |
+
candidate = raw.get("generation") if isinstance(raw, dict) else None
|
| 212 |
+
if isinstance(candidate, str) and SNAPSHOT_NAME_RE.fullmatch(candidate):
|
| 213 |
+
keep_generation = candidate
|
| 214 |
+
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
| 215 |
+
pass
|
| 216 |
+
try:
|
| 217 |
+
generations = bucket_dir / GENERATIONS_ROOT
|
| 218 |
+
if generations.is_dir():
|
| 219 |
+
for path in generations.iterdir():
|
| 220 |
+
if path.is_dir() and SNAPSHOT_NAME_RE.fullmatch(path.name) and path.name != keep_generation:
|
| 221 |
+
shutil.rmtree(path, ignore_errors=True)
|
| 222 |
+
for path in bucket_dir.glob(f".{MANIFEST_NAME}.*.tmp"):
|
| 223 |
+
path.unlink(missing_ok=True)
|
| 224 |
+
except OSError:
|
| 225 |
+
pass
|
| 226 |
+
try:
|
| 227 |
+
clear_directory(local_repository())
|
| 228 |
+
except OSError:
|
| 229 |
+
pass
|
| 230 |
|
| 231 |
def _publish(bucket_dir: Path) -> None:
|
| 232 |
if not bucket_dir.is_dir():
|
|
|
|
| 259 |
write_snapshot_status("publishing", stage="copy_generation", snapshot=snapshot)
|
| 260 |
generation_dir = bucket_dir / GENERATIONS_ROOT / generation
|
| 261 |
generation_dir.mkdir(parents=True, exist_ok=False)
|
| 262 |
+
shutil.copytree(local_repository(), generation_dir / REPOSITORY_DIRNAME, copy_function=link_or_copy)
|
| 263 |
sidecars: dict[str, dict[str, Any]] = {}
|
| 264 |
with tempfile.TemporaryDirectory(dir=DATA_ROOT, prefix="bha-snapshot-") as temporary_dir:
|
| 265 |
for key, source in SIDECARS.items():
|
|
|
|
| 293 |
shutil.rmtree(legacy_repository)
|
| 294 |
except Exception as exc:
|
| 295 |
print(f"bha_bucket_snapshot=cleanup_failed error={type(exc).__name__}", flush=True)
|
| 296 |
+
try:
|
| 297 |
+
clear_directory(local_repository())
|
| 298 |
+
except OSError as exc:
|
| 299 |
+
print(f"bha_bucket_snapshot=local_repository_cleanup_failed error={type(exc).__name__}", flush=True)
|
| 300 |
print(f"bha_bucket_snapshot=published snapshot={snapshot} elapsed_seconds={time.monotonic() - started:.2f}", flush=True)
|
| 301 |
|
| 302 |
|
|
|
|
| 304 |
generation_dir = bucket_dir / GENERATIONS_ROOT / str(manifest["generation"])
|
| 305 |
DATA_ROOT.mkdir(parents=True, exist_ok=True)
|
| 306 |
temporary_paths: list[tuple[Path, Path]] = []
|
| 307 |
+
replaced_targets: list[Path] = []
|
| 308 |
try:
|
| 309 |
for key, target in SIDECARS.items():
|
| 310 |
metadata = manifest["sidecars"][key]
|
|
|
|
| 327 |
Path(f"{target}-shm").unlink(missing_ok=True)
|
| 328 |
for temporary, target in temporary_paths:
|
| 329 |
os.replace(temporary, target)
|
| 330 |
+
replaced_targets.append(target)
|
| 331 |
except Exception:
|
| 332 |
+
for target in replaced_targets:
|
| 333 |
target.unlink(missing_ok=True)
|
| 334 |
for backup, target in backups:
|
| 335 |
os.replace(backup, target)
|
|
|
|
| 378 |
write_snapshot_status("unavailable", stage="read_manifest", reason="missing_or_invalid_manifest")
|
| 379 |
print("bha_bucket_snapshot=unavailable reason=missing_or_invalid_manifest", flush=True)
|
| 380 |
return False
|
| 381 |
+
source_stale = False
|
| 382 |
try:
|
| 383 |
remote_commits = {str(key): value for key, value in parsed_archive_commits(remote=True).items()}
|
| 384 |
if manifest["archive_commits"] != remote_commits:
|
|
|
|
| 386 |
write_snapshot_status("unavailable", stage="validate_source", reason="source_fingerprint_mismatch")
|
| 387 |
print("bha_bucket_snapshot=unavailable reason=source_fingerprint_mismatch", flush=True)
|
| 388 |
return False
|
| 389 |
+
source_stale = True
|
| 390 |
write_snapshot_status("stale_source", stage="validate_source", reason="source_fingerprint_mismatch")
|
| 391 |
print("bha_bucket_snapshot=stale_source reason=source_fingerprint_mismatch", flush=True)
|
| 392 |
except Exception as exc:
|
| 393 |
if allow_stale:
|
| 394 |
+
source_stale = True
|
| 395 |
write_snapshot_status("source_fingerprint_unverified", stage="validate_source", reason=type(exc).__name__)
|
| 396 |
print(f"bha_bucket_snapshot=source_fingerprint_unverified reason={type(exc).__name__}", flush=True)
|
| 397 |
else:
|
|
|
|
| 463 |
clear_directory(local_repository())
|
| 464 |
write_snapshot_status(
|
| 465 |
"restored", stage="complete", snapshot=str(manifest["snapshot"]),
|
| 466 |
+
elapsed_seconds=round(time.monotonic() - started, 2), source_stale=source_stale,
|
| 467 |
)
|
| 468 |
print(f"bha_bucket_snapshot=restored snapshot={manifest['snapshot']} elapsed_seconds={time.monotonic() - started:.2f}", flush=True)
|
| 469 |
return True
|
app/data_loader.py
CHANGED
|
@@ -5,6 +5,7 @@ import re
|
|
| 5 |
import shutil
|
| 6 |
import subprocess
|
| 7 |
import unicodedata
|
|
|
|
| 8 |
from pathlib import Path
|
| 9 |
from typing import Any, Callable, Iterator, Iterable
|
| 10 |
import jieba
|
|
@@ -14,6 +15,11 @@ CJK_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]+")
|
|
| 14 |
SEARCH_RUN_RE = re.compile(r"[a-z0-9]+|[\u3400-\u4dbf\u4e00-\u9fff]+", re.IGNORECASE)
|
| 15 |
DOCUMENT_BUILD_VERSION = "1"
|
| 16 |
PARSED_CACHE_ROOT = Path(os.environ["BHA_PARSED_CACHE_ROOT"]) if os.environ.get("BHA_PARSED_CACHE_ROOT") else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
def initialize_search_tokenizer() -> None:
|
| 19 |
jieba.initialize()
|
|
@@ -21,6 +27,12 @@ def initialize_search_tokenizer() -> None:
|
|
| 21 |
def run(command: list[str], cwd: Path | None = None) -> None:
|
| 22 |
subprocess.run(command, cwd=str(cwd) if cwd else None, check=True)
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
def cache_parsed_repository(source: Path, archive_id: int) -> None:
|
| 25 |
if PARSED_CACHE_ROOT is None:
|
| 26 |
return
|
|
@@ -33,7 +45,7 @@ def cache_parsed_repository(source: Path, archive_id: int) -> None:
|
|
| 33 |
return
|
| 34 |
temporary = PARSED_CACHE_ROOT / f".archives{archive_id}.{os.getpid()}.tmp"
|
| 35 |
shutil.rmtree(temporary, ignore_errors=True)
|
| 36 |
-
shutil.copytree(source, temporary)
|
| 37 |
shutil.rmtree(target, ignore_errors=True)
|
| 38 |
temporary.replace(target)
|
| 39 |
|
|
@@ -82,7 +94,7 @@ def ensure_parsed_data(
|
|
| 82 |
shutil.rmtree(target)
|
| 83 |
cached = PARSED_CACHE_ROOT / f"archives{archive_id}" if PARSED_CACHE_ROOT is not None else None
|
| 84 |
if cached is not None and cached.is_dir() and (cached / ".git").exists():
|
| 85 |
-
shutil.copytree(cached, target)
|
| 86 |
else:
|
| 87 |
run(["git", "clone", "--depth", "1", "--branch", "parsed", repo, str(target)])
|
| 88 |
expected = expected_commits.get(archive_id) if expected_commits else None
|
|
@@ -125,17 +137,9 @@ def parsed_archive_revisions(remote: bool = False, archive_ids: Iterable[int] |
|
|
| 125 |
|
| 126 |
def parsed_archive_commits(remote: bool = False, archive_ids: Iterable[int] | None = None) -> dict[int, str]:
|
| 127 |
revisions: dict[int, str] = {}
|
| 128 |
-
selected = archive_ids if archive_ids is not None else range(ARCHIVE_START, ARCHIVE_END + 1)
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
result = subprocess.run(
|
| 132 |
-
["git", "ls-remote", f"{REPO_PREFIX}/banned-historical-archives{archive_id}.git", "refs/heads/parsed"],
|
| 133 |
-
check=True,
|
| 134 |
-
capture_output=True,
|
| 135 |
-
text=True,
|
| 136 |
-
)
|
| 137 |
-
revision = result.stdout.split(maxsplit=1)[0]
|
| 138 |
-
else:
|
| 139 |
result = subprocess.run(
|
| 140 |
["git", "rev-parse", "HEAD"],
|
| 141 |
cwd=PARSED_ROOT / f"archives{archive_id}",
|
|
@@ -144,9 +148,27 @@ def parsed_archive_commits(remote: bool = False, archive_ids: Iterable[int] | No
|
|
| 144 |
text=True,
|
| 145 |
)
|
| 146 |
revision = result.stdout.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
if not re.fullmatch(r"[0-9a-f]{40}", revision):
|
| 148 |
raise RuntimeError(f"invalid parsed commit for archive {archive_id}")
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
return revisions
|
| 151 |
|
| 152 |
def read_json(path: Path) -> Any:
|
|
@@ -330,3 +352,17 @@ def iter_documents(
|
|
| 330 |
"path": str(article_path.relative_to(archive_root)),
|
| 331 |
"article": {**article, "tags": tags},
|
| 332 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import shutil
|
| 6 |
import subprocess
|
| 7 |
import unicodedata
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
from pathlib import Path
|
| 10 |
from typing import Any, Callable, Iterator, Iterable
|
| 11 |
import jieba
|
|
|
|
| 15 |
SEARCH_RUN_RE = re.compile(r"[a-z0-9]+|[\u3400-\u4dbf\u4e00-\u9fff]+", re.IGNORECASE)
|
| 16 |
DOCUMENT_BUILD_VERSION = "1"
|
| 17 |
PARSED_CACHE_ROOT = Path(os.environ["BHA_PARSED_CACHE_ROOT"]) if os.environ.get("BHA_PARSED_CACHE_ROOT") else None
|
| 18 |
+
try:
|
| 19 |
+
REMOTE_GIT_TIMEOUT_SECONDS = max(1, int(os.environ.get("BHA_REMOTE_GIT_TIMEOUT_SECONDS", "30")))
|
| 20 |
+
except ValueError:
|
| 21 |
+
REMOTE_GIT_TIMEOUT_SECONDS = 30
|
| 22 |
+
REMOTE_GIT_WORKERS = 8
|
| 23 |
|
| 24 |
def initialize_search_tokenizer() -> None:
|
| 25 |
jieba.initialize()
|
|
|
|
| 27 |
def run(command: list[str], cwd: Path | None = None) -> None:
|
| 28 |
subprocess.run(command, cwd=str(cwd) if cwd else None, check=True)
|
| 29 |
|
| 30 |
+
def link_or_copy(source: str | os.PathLike[str], destination: str | os.PathLike[str]) -> None:
|
| 31 |
+
try:
|
| 32 |
+
os.link(source, destination)
|
| 33 |
+
except OSError:
|
| 34 |
+
shutil.copy2(source, destination)
|
| 35 |
+
|
| 36 |
def cache_parsed_repository(source: Path, archive_id: int) -> None:
|
| 37 |
if PARSED_CACHE_ROOT is None:
|
| 38 |
return
|
|
|
|
| 45 |
return
|
| 46 |
temporary = PARSED_CACHE_ROOT / f".archives{archive_id}.{os.getpid()}.tmp"
|
| 47 |
shutil.rmtree(temporary, ignore_errors=True)
|
| 48 |
+
shutil.copytree(source, temporary, copy_function=link_or_copy)
|
| 49 |
shutil.rmtree(target, ignore_errors=True)
|
| 50 |
temporary.replace(target)
|
| 51 |
|
|
|
|
| 94 |
shutil.rmtree(target)
|
| 95 |
cached = PARSED_CACHE_ROOT / f"archives{archive_id}" if PARSED_CACHE_ROOT is not None else None
|
| 96 |
if cached is not None and cached.is_dir() and (cached / ".git").exists():
|
| 97 |
+
shutil.copytree(cached, target, copy_function=link_or_copy)
|
| 98 |
else:
|
| 99 |
run(["git", "clone", "--depth", "1", "--branch", "parsed", repo, str(target)])
|
| 100 |
expected = expected_commits.get(archive_id) if expected_commits else None
|
|
|
|
| 137 |
|
| 138 |
def parsed_archive_commits(remote: bool = False, archive_ids: Iterable[int] | None = None) -> dict[int, str]:
|
| 139 |
revisions: dict[int, str] = {}
|
| 140 |
+
selected = list(archive_ids) if archive_ids is not None else list(range(ARCHIVE_START, ARCHIVE_END + 1))
|
| 141 |
+
if not remote:
|
| 142 |
+
for archive_id in selected:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
result = subprocess.run(
|
| 144 |
["git", "rev-parse", "HEAD"],
|
| 145 |
cwd=PARSED_ROOT / f"archives{archive_id}",
|
|
|
|
| 148 |
text=True,
|
| 149 |
)
|
| 150 |
revision = result.stdout.strip()
|
| 151 |
+
if not re.fullmatch(r"[0-9a-f]{40}", revision):
|
| 152 |
+
raise RuntimeError(f"invalid parsed commit for archive {archive_id}")
|
| 153 |
+
revisions[archive_id] = revision
|
| 154 |
+
return revisions
|
| 155 |
+
|
| 156 |
+
def fetch_remote(archive_id: int) -> tuple[int, str]:
|
| 157 |
+
result = subprocess.run(
|
| 158 |
+
["git", "ls-remote", f"{REPO_PREFIX}/banned-historical-archives{archive_id}.git", "refs/heads/parsed"],
|
| 159 |
+
check=True,
|
| 160 |
+
capture_output=True,
|
| 161 |
+
text=True,
|
| 162 |
+
timeout=REMOTE_GIT_TIMEOUT_SECONDS,
|
| 163 |
+
)
|
| 164 |
+
revision = result.stdout.split(maxsplit=1)[0]
|
| 165 |
if not re.fullmatch(r"[0-9a-f]{40}", revision):
|
| 166 |
raise RuntimeError(f"invalid parsed commit for archive {archive_id}")
|
| 167 |
+
return archive_id, revision
|
| 168 |
+
|
| 169 |
+
with ThreadPoolExecutor(max_workers=min(REMOTE_GIT_WORKERS, max(1, len(selected)))) as executor:
|
| 170 |
+
for archive_id, revision in executor.map(fetch_remote, selected):
|
| 171 |
+
revisions[archive_id] = revision
|
| 172 |
return revisions
|
| 173 |
|
| 174 |
def read_json(path: Path) -> Any:
|
|
|
|
| 352 |
"path": str(article_path.relative_to(archive_root)),
|
| 353 |
"article": {**article, "tags": tags},
|
| 354 |
}
|
| 355 |
+
|
| 356 |
+
def iter_document_ids(archive_ids: Iterable[int] | None = None) -> Iterator[str]:
|
| 357 |
+
selected_archives = (
|
| 358 |
+
sorted(set(archive_ids)) if archive_ids is not None else range(ARCHIVE_START, ARCHIVE_END + 1)
|
| 359 |
+
)
|
| 360 |
+
for archive_id in selected_archives:
|
| 361 |
+
archive_root = PARSED_ROOT / f"archives{archive_id}"
|
| 362 |
+
if not archive_root.exists():
|
| 363 |
+
continue
|
| 364 |
+
for metadata_path in archive_root.glob("*/*/*.metadata"):
|
| 365 |
+
publication_id = metadata_path.stem
|
| 366 |
+
for article_path in metadata_path.parent.glob("*/*.json"):
|
| 367 |
+
article_id = article_path.stem
|
| 368 |
+
yield f"{archive_id}:{len(article_id)}:{article_id}:{publication_id}"
|
app/doc_store.py
CHANGED
|
@@ -40,6 +40,7 @@ def init_db(conn: sqlite3.Connection) -> None:
|
|
| 40 |
);
|
| 41 |
CREATE INDEX IF NOT EXISTS idx_docs_title ON docs(title);
|
| 42 |
CREATE INDEX IF NOT EXISTS idx_docs_publication_name ON docs(publication_name);
|
|
|
|
| 43 |
"""
|
| 44 |
)
|
| 45 |
columns = {row[1] for row in conn.execute("PRAGMA table_info(docs)")}
|
|
|
|
| 40 |
);
|
| 41 |
CREATE INDEX IF NOT EXISTS idx_docs_title ON docs(title);
|
| 42 |
CREATE INDEX IF NOT EXISTS idx_docs_publication_name ON docs(publication_name);
|
| 43 |
+
CREATE INDEX IF NOT EXISTS idx_docs_archive_id ON docs(archive_id);
|
| 44 |
"""
|
| 45 |
)
|
| 46 |
columns = {row[1] for row in conn.execute("PRAGMA table_info(docs)")}
|
app/facet_store.py
CHANGED
|
@@ -30,6 +30,7 @@ def init_db(conn: sqlite3.Connection) -> None:
|
|
| 30 |
PRIMARY KEY (kind, name)
|
| 31 |
);
|
| 32 |
CREATE INDEX IF NOT EXISTS idx_facets_kind_name ON facets(kind, name);
|
|
|
|
| 33 |
"""
|
| 34 |
)
|
| 35 |
|
|
|
|
| 30 |
PRIMARY KEY (kind, name)
|
| 31 |
);
|
| 32 |
CREATE INDEX IF NOT EXISTS idx_facets_kind_name ON facets(kind, name);
|
| 33 |
+
CREATE INDEX IF NOT EXISTS idx_facets_kind_name_nocase ON facets(kind, name COLLATE NOCASE);
|
| 34 |
"""
|
| 35 |
)
|
| 36 |
|
app/indexer.py
CHANGED
|
@@ -13,7 +13,7 @@ from typing import IO, Iterable
|
|
| 13 |
from elasticsearch import Elasticsearch, helpers
|
| 14 |
from elasticsearch.exceptions import NotFoundError
|
| 15 |
from .config import DATA_ROOT, ARCHIVE_END, ARCHIVE_START, ES_URL, INDEX_NAME, INDEX_VERSION, RESET_INDEX
|
| 16 |
-
from .data_loader import DOCUMENT_BUILD_VERSION, ensure_parsed_data, iter_documents, parsed_archive_commits, parsed_archive_revisions, parsed_corpus_fingerprint
|
| 17 |
from .doc_store import DOC_DB, DOC_STORE_SCHEMA_VERSION, connect as connect_doc_db, delete_docs_to_conn, doc_row, init_db as init_doc_db, reset_db, row_to_doc, update_years_to_conn, write_docs_to_conn
|
| 18 |
from .facet_store import FACET_DB, FACET_STORE_SCHEMA_VERSION, apply_facet_deltas, connect as connect_facet_db, init_db as init_facet_db, reset_db as reset_facet_db, write_facets
|
| 19 |
from .storage_lock import serving_lock
|
|
@@ -238,16 +238,30 @@ def incremental_build(
|
|
| 238 |
raise IncrementalUnsafe("serving sidecar generation is unavailable")
|
| 239 |
removed_docs: list[dict] = []
|
| 240 |
upsert_docs: list[dict] = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
with connect_doc_db(temp_doc_db) as conn:
|
| 242 |
init_doc_db(conn)
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
seen_ids: set[str] = set()
|
| 250 |
-
|
|
|
|
|
|
|
| 251 |
doc_id = doc["doc_id"]
|
| 252 |
if doc_id in seen_ids:
|
| 253 |
raise IncrementalUnsafe(f"duplicate incremental doc_id: {doc_id}")
|
|
@@ -682,6 +696,12 @@ def _ensure_index(
|
|
| 682 |
if error_count:
|
| 683 |
write_progress(status="failed", indexed=ok, errors=error_count, elapsed_seconds=int(time.time() - started_at))
|
| 684 |
raise RuntimeError(f"bulk indexing failed with {error_count} errors")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 685 |
write_facets(facet_counters, temp_facet_db)
|
| 686 |
es.index(index=build_index, id="__meta__", document=desired_metadata(source_fingerprint, archive_revisions))
|
| 687 |
with connect_doc_db(temp_doc_db) as conn:
|
|
|
|
| 13 |
from elasticsearch import Elasticsearch, helpers
|
| 14 |
from elasticsearch.exceptions import NotFoundError
|
| 15 |
from .config import DATA_ROOT, ARCHIVE_END, ARCHIVE_START, ES_URL, INDEX_NAME, INDEX_VERSION, RESET_INDEX
|
| 16 |
+
from .data_loader import DOCUMENT_BUILD_VERSION, ensure_parsed_data, iter_document_ids, iter_documents, parsed_archive_commits, parsed_archive_revisions, parsed_corpus_fingerprint
|
| 17 |
from .doc_store import DOC_DB, DOC_STORE_SCHEMA_VERSION, connect as connect_doc_db, delete_docs_to_conn, doc_row, init_db as init_doc_db, reset_db, row_to_doc, update_years_to_conn, write_docs_to_conn
|
| 18 |
from .facet_store import FACET_DB, FACET_STORE_SCHEMA_VERSION, apply_facet_deltas, connect as connect_facet_db, init_db as init_facet_db, reset_db as reset_facet_db, write_facets
|
| 19 |
from .storage_lock import serving_lock
|
|
|
|
| 238 |
raise IncrementalUnsafe("serving sidecar generation is unavailable")
|
| 239 |
removed_docs: list[dict] = []
|
| 240 |
upsert_docs: list[dict] = []
|
| 241 |
+
scan_archives = changed
|
| 242 |
+
if changed_paths is not None:
|
| 243 |
+
# A changed-path filter cannot identify deletions without seeing the
|
| 244 |
+
# complete current archive. Empty diffs are safe to skip.
|
| 245 |
+
scan_archives = [
|
| 246 |
+
archive_id for archive_id in changed
|
| 247 |
+
if changed_paths.get(archive_id) is None or changed_paths[archive_id]
|
| 248 |
+
]
|
| 249 |
with connect_doc_db(temp_doc_db) as conn:
|
| 250 |
init_doc_db(conn)
|
| 251 |
+
remaining_ids: set[str] = set()
|
| 252 |
+
if scan_archives:
|
| 253 |
+
placeholders = ",".join("?" for _ in scan_archives)
|
| 254 |
+
old_ids = {
|
| 255 |
+
row[0] for row in conn.execute(
|
| 256 |
+
f"SELECT doc_id FROM docs WHERE archive_id IN ({placeholders})", scan_archives
|
| 257 |
+
)
|
| 258 |
+
}
|
| 259 |
+
current_ids = set(iter_document_ids(scan_archives))
|
| 260 |
+
remaining_ids = old_ids - current_ids
|
| 261 |
seen_ids: set[str] = set()
|
| 262 |
+
# File paths identify deletions cheaply; only changed files need
|
| 263 |
+
# JSON normalization and tokenization.
|
| 264 |
+
for doc in iter_documents(scan_archives, changed_paths=changed_paths):
|
| 265 |
doc_id = doc["doc_id"]
|
| 266 |
if doc_id in seen_ids:
|
| 267 |
raise IncrementalUnsafe(f"duplicate incremental doc_id: {doc_id}")
|
|
|
|
| 696 |
if error_count:
|
| 697 |
write_progress(status="failed", indexed=ok, errors=error_count, elapsed_seconds=int(time.time() - started_at))
|
| 698 |
raise RuntimeError(f"bulk indexing failed with {error_count} errors")
|
| 699 |
+
with connect_doc_db(temp_doc_db) as conn:
|
| 700 |
+
sqlite_count = int(conn.execute("SELECT COUNT(*) FROM docs").fetchone()[0])
|
| 701 |
+
if sqlite_count != ok:
|
| 702 |
+
raise RuntimeError(
|
| 703 |
+
f"full build document count mismatch: indexed={ok} sqlite={sqlite_count}; duplicate doc_id likely"
|
| 704 |
+
)
|
| 705 |
write_facets(facet_counters, temp_facet_db)
|
| 706 |
es.index(index=build_index, id="__meta__", document=desired_metadata(source_fingerprint, archive_revisions))
|
| 707 |
with connect_doc_db(temp_doc_db) as conn:
|
app/main.py
CHANGED
|
@@ -12,6 +12,7 @@ import socket
|
|
| 12 |
import tempfile
|
| 13 |
import threading
|
| 14 |
import time
|
|
|
|
| 15 |
from urllib.parse import quote, unquote_to_bytes, urlparse
|
| 16 |
from typing import Any, Literal
|
| 17 |
from zipfile import ZIP_DEFLATED, ZipFile
|
|
@@ -30,8 +31,8 @@ from .doc_store import available_years, get_doc, random_doc, variants_for_title,
|
|
| 30 |
from .search_store import SearchStoreError, get_search_docs, literal_match_ids
|
| 31 |
from .data_loader import initialize_search_tokenizer, search_words
|
| 32 |
from .facet_store import FACET_DB, list_facets, sources_payload
|
| 33 |
-
from .indexer import acquire_index_lock, ensure_index
|
| 34 |
-
from .bucket_snapshot import publish as publish_bucket_snapshot, publish_due as bucket_snapshot_publish_due, snapshot_status as bucket_snapshot_status
|
| 35 |
from .storage_lock import serving_lock
|
| 36 |
SOURCE_MIRROR_MANIFEST_URL = os.environ.get(
|
| 37 |
"BHA_SOURCE_MIRROR_MANIFEST_URL",
|
|
@@ -47,9 +48,12 @@ source_mirror_loaded_at = 0.0
|
|
| 47 |
source_mirror_etag: str | None = None
|
| 48 |
source_mirror_refresh_task: asyncio.Task | None = None
|
| 49 |
source_mirror_lock = asyncio.Lock()
|
|
|
|
|
|
|
| 50 |
MAX_RESULT_WINDOW = 500000
|
| 51 |
REINDEX_COOLDOWN_SECONDS = 10 * 60
|
| 52 |
REINDEX_LAST_START = DATA_ROOT / "reindex-last-start"
|
|
|
|
| 53 |
REINDEX_TOKEN = os.environ.get("BHA_REINDEX_TOKEN", "")
|
| 54 |
PROOFREAD_GITHUB_TOKEN = os.environ.get("BHA_PROOFREAD_GITHUB_TOKEN", "")
|
| 55 |
PROOFREAD_PIPELINE_REPOSITORY = os.environ.get("BHA_PROOFREAD_PIPELINE_REPOSITORY", "anftm/pipeline")
|
|
@@ -540,6 +544,32 @@ def clear_response_caches() -> None:
|
|
| 540 |
sources_response_cache = None
|
| 541 |
status_response_cache = None
|
| 542 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
def search_cache_key(body: SearchRequest, page: int, page_size: int) -> tuple[Any, ...]:
|
| 544 |
return (
|
| 545 |
body.q, page, page_size, body.exact, body.fulltext, body.sort,
|
|
@@ -623,6 +653,7 @@ async def initialize_when_ready() -> None:
|
|
| 623 |
|
| 624 |
async def start_ready_data_initialization():
|
| 625 |
await asyncio.to_thread(initialize_search_tokenizer)
|
|
|
|
| 626 |
asyncio.create_task(initialize_when_ready())
|
| 627 |
asyncio.create_task(auxiliary_warmup_loop())
|
| 628 |
asyncio.create_task(source_mirror_warmup_loop())
|
|
@@ -686,6 +717,13 @@ def index_ready() -> bool:
|
|
| 686 |
except Exception:
|
| 687 |
return False
|
| 688 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
def document_count() -> int:
|
| 690 |
try:
|
| 691 |
if not es.indices.exists(index=INDEX_NAME):
|
|
@@ -1842,14 +1880,53 @@ async def download_source_zip(doc_id: str):
|
|
| 1842 |
)
|
| 1843 |
|
| 1844 |
def publish_bucket_snapshot_worker() -> None:
|
|
|
|
|
|
|
|
|
|
| 1845 |
try:
|
| 1846 |
-
if BUCKET_DIR is
|
|
|
|
|
|
|
| 1847 |
publish_bucket_snapshot(BUCKET_DIR)
|
| 1848 |
-
|
| 1849 |
-
|
|
|
|
|
|
|
|
|
|
| 1850 |
except Exception as exc:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1851 |
print(f"bucket_snapshot_publish_failed={exc}")
|
| 1852 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1853 |
def run_reindex(
|
| 1854 |
lock_file,
|
| 1855 |
reset: bool = False,
|
|
@@ -1857,7 +1934,10 @@ def run_reindex(
|
|
| 1857 |
expected_revisions: dict[int, str] | None = None,
|
| 1858 |
changed_archives: list[int] | None = None,
|
| 1859 |
) -> None:
|
|
|
|
|
|
|
| 1860 |
try:
|
|
|
|
| 1861 |
INDEX_STATUS_PATH.write_text("rebuilding", encoding="utf-8")
|
| 1862 |
clear_response_caches()
|
| 1863 |
if expected_commits is None and expected_revisions is None:
|
|
@@ -1869,11 +1949,18 @@ def run_reindex(
|
|
| 1869 |
changed_archives=changed_archives,
|
| 1870 |
)
|
| 1871 |
INDEX_STATUS_PATH.write_text("ready", encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
| 1872 |
if changed and BUCKET_DIR is not None:
|
| 1873 |
threading.Thread(target=publish_bucket_snapshot_worker, daemon=True).start()
|
| 1874 |
except Exception as exc:
|
| 1875 |
-
safe_ready = not INDEX_SWITCH_STATE_PATH.exists() and
|
| 1876 |
INDEX_STATUS_PATH.write_text("ready" if safe_ready else "failed", encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1877 |
print(f"reindex_failed={exc}")
|
| 1878 |
finally:
|
| 1879 |
clear_response_caches()
|
|
@@ -1935,6 +2022,13 @@ def reindex(request: Request, full: bool = False, payload: ReindexRequest | None
|
|
| 1935 |
try:
|
| 1936 |
REINDEX_LAST_START.parent.mkdir(parents=True, exist_ok=True)
|
| 1937 |
REINDEX_LAST_START.write_text(str(now), encoding="utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1938 |
if payload is None:
|
| 1939 |
start_reindex_worker(lock_file, reset=full)
|
| 1940 |
else:
|
|
@@ -1951,6 +2045,7 @@ def reindex(request: Request, full: bool = False, payload: ReindexRequest | None
|
|
| 1951 |
"ok": True,
|
| 1952 |
"status": "accepted",
|
| 1953 |
"mode": "full" if full else "incremental",
|
|
|
|
| 1954 |
"cooldown_seconds": REINDEX_COOLDOWN_SECONDS,
|
| 1955 |
}
|
| 1956 |
|
|
@@ -1967,6 +2062,7 @@ def reindex_status(request: Request):
|
|
| 1967 |
return {
|
| 1968 |
"index_status": index_status(),
|
| 1969 |
"progress": index_progress(),
|
|
|
|
| 1970 |
"switch_pending": INDEX_SWITCH_STATE_PATH.exists(),
|
| 1971 |
"archive_revisions": metadata.get("archive_revisions") or {},
|
| 1972 |
"build_fingerprint": metadata.get("build_fingerprint"),
|
|
|
|
| 12 |
import tempfile
|
| 13 |
import threading
|
| 14 |
import time
|
| 15 |
+
import uuid
|
| 16 |
from urllib.parse import quote, unquote_to_bytes, urlparse
|
| 17 |
from typing import Any, Literal
|
| 18 |
from zipfile import ZIP_DEFLATED, ZipFile
|
|
|
|
| 31 |
from .search_store import SearchStoreError, get_search_docs, literal_match_ids
|
| 32 |
from .data_loader import initialize_search_tokenizer, search_words
|
| 33 |
from .facet_store import FACET_DB, list_facets, sources_payload
|
| 34 |
+
from .indexer import acquire_index_lock, ensure_index, sidecars_ready
|
| 35 |
+
from .bucket_snapshot import publish as publish_bucket_snapshot, publish_delay as bucket_snapshot_publish_delay, publish_due as bucket_snapshot_publish_due, snapshot_status as bucket_snapshot_status, write_snapshot_status
|
| 36 |
from .storage_lock import serving_lock
|
| 37 |
SOURCE_MIRROR_MANIFEST_URL = os.environ.get(
|
| 38 |
"BHA_SOURCE_MIRROR_MANIFEST_URL",
|
|
|
|
| 48 |
source_mirror_etag: str | None = None
|
| 49 |
source_mirror_refresh_task: asyncio.Task | None = None
|
| 50 |
source_mirror_lock = asyncio.Lock()
|
| 51 |
+
snapshot_publish_timer: threading.Timer | None = None
|
| 52 |
+
snapshot_publish_timer_lock = threading.Lock()
|
| 53 |
MAX_RESULT_WINDOW = 500000
|
| 54 |
REINDEX_COOLDOWN_SECONDS = 10 * 60
|
| 55 |
REINDEX_LAST_START = DATA_ROOT / "reindex-last-start"
|
| 56 |
+
REINDEX_JOB_PATH = DATA_ROOT / "reindex-job.json"
|
| 57 |
REINDEX_TOKEN = os.environ.get("BHA_REINDEX_TOKEN", "")
|
| 58 |
PROOFREAD_GITHUB_TOKEN = os.environ.get("BHA_PROOFREAD_GITHUB_TOKEN", "")
|
| 59 |
PROOFREAD_PIPELINE_REPOSITORY = os.environ.get("BHA_PROOFREAD_PIPELINE_REPOSITORY", "anftm/pipeline")
|
|
|
|
| 544 |
sources_response_cache = None
|
| 545 |
status_response_cache = None
|
| 546 |
|
| 547 |
+
def write_reindex_job(state: str, job_id: str, **values: Any) -> None:
|
| 548 |
+
previous = read_reindex_job() or {}
|
| 549 |
+
payload = {
|
| 550 |
+
**(previous if previous.get("job_id") == job_id else {}),
|
| 551 |
+
"job_id": job_id, "state": state, "updated_at": int(time.time()), **values,
|
| 552 |
+
}
|
| 553 |
+
REINDEX_JOB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 554 |
+
temporary = REINDEX_JOB_PATH.with_name(f".{REINDEX_JOB_PATH.name}.{uuid.uuid4().hex}.tmp")
|
| 555 |
+
temporary.write_text(json.dumps(payload, ensure_ascii=False, sort_keys=True), encoding="utf-8")
|
| 556 |
+
os.replace(temporary, REINDEX_JOB_PATH)
|
| 557 |
+
|
| 558 |
+
def read_reindex_job() -> dict[str, Any] | None:
|
| 559 |
+
try:
|
| 560 |
+
value = json.loads(REINDEX_JOB_PATH.read_text(encoding="utf-8"))
|
| 561 |
+
return value if isinstance(value, dict) else None
|
| 562 |
+
except (OSError, json.JSONDecodeError):
|
| 563 |
+
return None
|
| 564 |
+
|
| 565 |
+
def update_reindex_job(state: str, job_id: str, **values: Any) -> None:
|
| 566 |
+
if not job_id:
|
| 567 |
+
return
|
| 568 |
+
try:
|
| 569 |
+
write_reindex_job(state, job_id, **values)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
print(f"reindex_job_status_failed={type(exc).__name__}", flush=True)
|
| 572 |
+
|
| 573 |
def search_cache_key(body: SearchRequest, page: int, page_size: int) -> tuple[Any, ...]:
|
| 574 |
return (
|
| 575 |
body.q, page, page_size, body.exact, body.fulltext, body.sort,
|
|
|
|
| 653 |
|
| 654 |
async def start_ready_data_initialization():
|
| 655 |
await asyncio.to_thread(initialize_search_tokenizer)
|
| 656 |
+
resume_pending_snapshot_publish()
|
| 657 |
asyncio.create_task(initialize_when_ready())
|
| 658 |
asyncio.create_task(auxiliary_warmup_loop())
|
| 659 |
asyncio.create_task(source_mirror_warmup_loop())
|
|
|
|
| 717 |
except Exception:
|
| 718 |
return False
|
| 719 |
|
| 720 |
+
def serving_generation_valid() -> bool:
|
| 721 |
+
try:
|
| 722 |
+
metadata = es.get(index=INDEX_NAME, id="__meta__").get("_source", {})
|
| 723 |
+
return bool(metadata) and sidecars_ready(metadata)
|
| 724 |
+
except Exception:
|
| 725 |
+
return False
|
| 726 |
+
|
| 727 |
def document_count() -> int:
|
| 728 |
try:
|
| 729 |
if not es.indices.exists(index=INDEX_NAME):
|
|
|
|
| 1880 |
)
|
| 1881 |
|
| 1882 |
def publish_bucket_snapshot_worker() -> None:
|
| 1883 |
+
global snapshot_publish_timer
|
| 1884 |
+
with snapshot_publish_timer_lock:
|
| 1885 |
+
snapshot_publish_timer = None
|
| 1886 |
try:
|
| 1887 |
+
if BUCKET_DIR is None:
|
| 1888 |
+
return
|
| 1889 |
+
if bucket_snapshot_publish_due(BUCKET_DIR, SNAPSHOT_MIN_INTERVAL_SECONDS):
|
| 1890 |
publish_bucket_snapshot(BUCKET_DIR)
|
| 1891 |
+
return
|
| 1892 |
+
delay = bucket_snapshot_publish_delay(BUCKET_DIR, SNAPSHOT_MIN_INTERVAL_SECONDS)
|
| 1893 |
+
write_snapshot_status("pending_publish", retry_at=int(time.time()) + delay)
|
| 1894 |
+
print(f"bucket_snapshot_publish_scheduled=delay_{delay}", flush=True)
|
| 1895 |
+
schedule_bucket_snapshot_publish(delay)
|
| 1896 |
except Exception as exc:
|
| 1897 |
+
if BUCKET_DIR is not None:
|
| 1898 |
+
retry_delay = 300
|
| 1899 |
+
try:
|
| 1900 |
+
write_snapshot_status(
|
| 1901 |
+
"pending_publish", retry_at=int(time.time()) + retry_delay,
|
| 1902 |
+
last_error=f"{type(exc).__name__}: {str(exc)[:300]}",
|
| 1903 |
+
)
|
| 1904 |
+
schedule_bucket_snapshot_publish(retry_delay)
|
| 1905 |
+
except Exception:
|
| 1906 |
+
pass
|
| 1907 |
print(f"bucket_snapshot_publish_failed={exc}")
|
| 1908 |
|
| 1909 |
+
def schedule_bucket_snapshot_publish(delay: int) -> None:
|
| 1910 |
+
global snapshot_publish_timer
|
| 1911 |
+
with snapshot_publish_timer_lock:
|
| 1912 |
+
if snapshot_publish_timer is not None and snapshot_publish_timer.is_alive():
|
| 1913 |
+
return
|
| 1914 |
+
snapshot_publish_timer = threading.Timer(max(1, delay), publish_bucket_snapshot_worker)
|
| 1915 |
+
snapshot_publish_timer.daemon = True
|
| 1916 |
+
snapshot_publish_timer.start()
|
| 1917 |
+
|
| 1918 |
+
def resume_pending_snapshot_publish() -> None:
|
| 1919 |
+
if BUCKET_DIR is None:
|
| 1920 |
+
return
|
| 1921 |
+
status = bucket_snapshot_status() or {}
|
| 1922 |
+
if status.get("state") != "pending_publish":
|
| 1923 |
+
return
|
| 1924 |
+
try:
|
| 1925 |
+
delay = max(0, int(status.get("retry_at", 0)) - int(time.time()))
|
| 1926 |
+
except (TypeError, ValueError):
|
| 1927 |
+
delay = 0
|
| 1928 |
+
schedule_bucket_snapshot_publish(delay)
|
| 1929 |
+
|
| 1930 |
def run_reindex(
|
| 1931 |
lock_file,
|
| 1932 |
reset: bool = False,
|
|
|
|
| 1934 |
expected_revisions: dict[int, str] | None = None,
|
| 1935 |
changed_archives: list[int] | None = None,
|
| 1936 |
) -> None:
|
| 1937 |
+
job = read_reindex_job()
|
| 1938 |
+
job_id = str(job.get("job_id")) if job and job.get("job_id") else ""
|
| 1939 |
try:
|
| 1940 |
+
update_reindex_job("running", job_id, started_at=int(time.time()))
|
| 1941 |
INDEX_STATUS_PATH.write_text("rebuilding", encoding="utf-8")
|
| 1942 |
clear_response_caches()
|
| 1943 |
if expected_commits is None and expected_revisions is None:
|
|
|
|
| 1949 |
changed_archives=changed_archives,
|
| 1950 |
)
|
| 1951 |
INDEX_STATUS_PATH.write_text("ready", encoding="utf-8")
|
| 1952 |
+
update_reindex_job(
|
| 1953 |
+
"succeeded", job_id, changed=bool(changed), index_status="ready", finished_at=int(time.time()),
|
| 1954 |
+
)
|
| 1955 |
if changed and BUCKET_DIR is not None:
|
| 1956 |
threading.Thread(target=publish_bucket_snapshot_worker, daemon=True).start()
|
| 1957 |
except Exception as exc:
|
| 1958 |
+
safe_ready = not INDEX_SWITCH_STATE_PATH.exists() and serving_generation_valid()
|
| 1959 |
INDEX_STATUS_PATH.write_text("ready" if safe_ready else "failed", encoding="utf-8")
|
| 1960 |
+
update_reindex_job(
|
| 1961 |
+
"failed", job_id, error=f"{type(exc).__name__}: {str(exc)[:500]}",
|
| 1962 |
+
index_status="ready" if safe_ready else "failed", finished_at=int(time.time()),
|
| 1963 |
+
)
|
| 1964 |
print(f"reindex_failed={exc}")
|
| 1965 |
finally:
|
| 1966 |
clear_response_caches()
|
|
|
|
| 2022 |
try:
|
| 2023 |
REINDEX_LAST_START.parent.mkdir(parents=True, exist_ok=True)
|
| 2024 |
REINDEX_LAST_START.write_text(str(now), encoding="utf-8")
|
| 2025 |
+
job_id = uuid.uuid4().hex
|
| 2026 |
+
write_reindex_job(
|
| 2027 |
+
"accepted", job_id, mode="full" if full else "incremental",
|
| 2028 |
+
changed_archives=changed_archives or [],
|
| 2029 |
+
target_archive_revisions=expected_revisions or {},
|
| 2030 |
+
accepted_at=now,
|
| 2031 |
+
)
|
| 2032 |
if payload is None:
|
| 2033 |
start_reindex_worker(lock_file, reset=full)
|
| 2034 |
else:
|
|
|
|
| 2045 |
"ok": True,
|
| 2046 |
"status": "accepted",
|
| 2047 |
"mode": "full" if full else "incremental",
|
| 2048 |
+
"job_id": job_id,
|
| 2049 |
"cooldown_seconds": REINDEX_COOLDOWN_SECONDS,
|
| 2050 |
}
|
| 2051 |
|
|
|
|
| 2062 |
return {
|
| 2063 |
"index_status": index_status(),
|
| 2064 |
"progress": index_progress(),
|
| 2065 |
+
"job": read_reindex_job(),
|
| 2066 |
"switch_pending": INDEX_SWITCH_STATE_PATH.exists(),
|
| 2067 |
"archive_revisions": metadata.get("archive_revisions") or {},
|
| 2068 |
"build_fingerprint": metadata.get("build_fingerprint"),
|