From 492987100cfe2611035d48cbd8e133311a1e0e1b Mon Sep 17 00:00:00 2001 From: genja Date: Mon, 16 Nov 2026 14:43:12 +0100 Subject: [PATCH] added verified persons job --- .dockerignore | 6 + .gitignore | 3 + service/scripts/jobs-image/README.md | 29 + .../orgminer-verified-persons-ude/Dockerfile | 27 + .../requirements.txt | 5 + .../README.md | 56 ++ .../upload_orgminer_verified_persons_ude.py | 917 ++++++++++++++++++ 7 files changed, 1043 insertions(+) create mode 100644 service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile create mode 100644 service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt create mode 100644 service/scripts/upload_orgminer_verified_persons_ude/README.md create mode 100644 service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py diff --git a/.dockerignore b/.dockerignore index 957438e1..7d14381e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,3 +1,4 @@ +# Root-context job images only need service code, never the webapp or repo data. * !background-jobs !service @@ -7,6 +8,11 @@ service/* # Keyword extraction contract, shared with background-jobs/app/llm/client.py. !service/src/main/inse/news/keyword_extraction.py +# UDE verified-persons job image imports the full service package and one +# institution hierarchy, so these are the only extra paths it needs. +!service/src/main/inse +!service/src/data/hierarchies/I62318514/hierarchy.json + # Data-only folders that do not belong in the job image. service/scripts/multipliers diff --git a/.gitignore b/.gitignore index fe6b79ff..77260b1e 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,6 @@ service/sentence_transformer/models/ llm_evaluations/bio_generation/.venv .devcontainer +# Runtime checkpoint for the UDE OrgMiner verified-person uploader. +service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json +service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json.tmp diff --git a/service/scripts/jobs-image/README.md b/service/scripts/jobs-image/README.md index dfe8da7e..d0c7a4e0 100644 --- a/service/scripts/jobs-image/README.md +++ b/service/scripts/jobs-image/README.md @@ -82,6 +82,7 @@ differ only by their `command`. | Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend | | News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend | | News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index | +| UDE OrgMiner Verified Persons | `jobs/orgminer-verified-persons-ude` | `upload_orgminer_verified_persons_ude.py --progress-file /state/orgminer_verified_persons_ude_progress.json` | Writes `orgminer_verified_persons_ude`; image-scoped NES creds; persistent checkpoint | | Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows | Each image is its own repository under the `jobs/` path namespace, prefixed @@ -106,6 +107,30 @@ docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest Each image's Dockerfile header lists its own build command. +### UDE OrgMiner verified persons + +```bash +docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \ + -t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest . +docker push docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest +``` + +Create a manual-only job in the Jobs UI with this image and set **Persistent +directory** to `/state`. The image's entrypoint writes its JSON checkpoint to +`/state/orgminer_verified_persons_ude_progress.json`; the runner mounts a task-specific Docker volume there so +separate runs resume. Keep the job definition if you need to keep its checkpoint +(deleting the definition also removes its volume). Leave **Command** empty for a +full resumable run, or set it to `--limit 5` for a small first run. Set **Command** +to `--fresh` if every invocation should delete the checkpoint and start at the +first organization. Organizations are processed sequentially; no concurrency +flags exist. The target index is `orgminer_verified_persons_ude`. + +If the run stops without a `Finished:` line and reports exit `137`, the +container was killed (usually by the host's out-of-memory killer) and no Python +traceback exists. The run log then gets a `[system] ... ran out of memory ...` +note from the runner. A job without a **Persistent directory** always starts +from the first organization, which makes such a restart look identical. + ## Running locally without pushing Before each run the backend pulls the job's image from the registry when it is a @@ -127,6 +152,10 @@ is enough for local runs. Because every tag lives under the `docker.nes.uni-due.de` registry host, the backend treats these as registry images and injects the INSE Elasticsearch / LLM credentials automatically (plus any per-job `env`). +The `orgminer-verified-persons-ude` image also receives `ELASTICSEARCH_URL` and +`ELASTICSEARCH_API_KEY` from backend settings, and only that exact repository +gets those NES credentials. Other job images continue to receive INSE/LLM +credentials only. Most images write to the test index by default: the crawlers upload into the index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to diff --git a/service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile b/service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile new file mode 100644 index 00000000..a02f3cd0 --- /dev/null +++ b/service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile @@ -0,0 +1,27 @@ +# UDE OrgMiner staff verification using the collaboration graph. +# Build from the repository root: +# docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \ +# -t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest . +# +# The runner injects INSE credentials for registry images and NES credentials +# only for this image. The persistent /state volume holds the JSON checkpoint. +FROM python:3.13-slim + +WORKDIR /app +ENV PYTHONUNBUFFERED=1 \ + PYTHONPATH=/app/service/src/main + +COPY service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY service/src/main/inse/ ./service/src/main/inse/ +COPY service/src/data/hierarchies/I62318514/hierarchy.json \ + ./service/src/data/hierarchies/I62318514/hierarchy.json +COPY service/scripts/upload_orgminer_verified_persons_ude/ \ + ./service/scripts/upload_orgminer_verified_persons_ude/ + +# Fail the image build if the service verification code is missing a dependency. +RUN python -c "import inse.orgminer.logic" + +ENTRYPOINT ["python", "/app/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py", \ + "--progress-file", "/state/orgminer_verified_persons_ude_progress.json"] diff --git a/service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt b/service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt new file mode 100644 index 00000000..8311e70a --- /dev/null +++ b/service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt @@ -0,0 +1,5 @@ +fastapi~=0.115.0 +httpx~=0.27.0 +pydantic-settings~=2.2.1 +python-dotenv~=1.0 +sqlmodel~=0.0.33 diff --git a/service/scripts/upload_orgminer_verified_persons_ude/README.md b/service/scripts/upload_orgminer_verified_persons_ude/README.md new file mode 100644 index 00000000..f94dd8ef --- /dev/null +++ b/service/scripts/upload_orgminer_verified_persons_ude/README.md @@ -0,0 +1,56 @@ +# Upload verified UDE OrgMiner persons + +Run from the repository root: + +```bash +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py +``` + +The script reads `ude_organization_content_august_2025_draft`, applies the +OrgMiner collaboration-graph verification rule, and upserts one document per +verified OpenAlex person and organization into `orgminer_verified_persons_ude` +on the INSE Elasticsearch cluster. + +For the background-job image and persistent checkpoint setup, see +[`../jobs-image/README.md`](../jobs-image/README.md#ude-orgminer-verified-persons). + +INSE credentials must be available as `ELASTICSEARCH_INSE_URL` and +`ELASTICSEARCH_INSE_API_KEY` for reading/writing OrgMiner data. NES credentials +must also be available as `ELASTICSEARCH_URL` and `ELASTICSEARCH_API_KEY` for +OpenAlex author resolution during verification. They can be set in the +environment or the service `.env` file. + +The default checkpoint is `orgminer_verified_persons_ude_progress.json` next to +the script. It records completed source organization document IDs and the last +completed organization URI. On restart the scan resumes from that URI, skips +completed organizations, and safely retries upserts if an interrupted request did +not get checkpointed. Use `--progress-file PATH` to keep the checkpoint elsewhere. + +The script processes one organization at a time, so a run needs no concurrency +flags. + +Useful options: + +```bash +# Run verification without writing to Elasticsearch or changing the checkpoint +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --dry-run + +# Smoke-test a limited number of pending organizations +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --limit 5 + +# Delete the checkpoint and scan from the first organization again +python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh +``` + +Verification requests only the collaboration weights towards the organization's +other staff candidates. It does not materialize every co-author pair, which is +unbounded for works with hundreds or thousands of authors. The progress log ends +each line with the process's peak `rss` so memory growth is visible. + +`--fresh` removes the selected checkpoint and its temporary atomic-write file, +but does not clear the output index. Existing person/organization IDs are +upserted; output documents that are no longer produced are left in the index. +When configured on a background-job task, `--fresh` applies on every run, so the +task always restarts from the first source organization. If the checkpoint +directory is not a mounted volume, a warning is logged because progress cannot +survive the container. diff --git a/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py b/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py new file mode 100644 index 00000000..6e8e2a38 --- /dev/null +++ b/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py @@ -0,0 +1,917 @@ +"""Upload UDE OrgMiner staff that were verified by the collaboration graph. + +What this script does +--------------------- +For every organization in the UDE organization-content index (one at a time): + + 1. READ the organization and its staff list from Elasticsearch (INSE) + 2. VERIFY each staff member against the collaboration graph (OpenAlex) + 3. BUILD one document per (organization, OpenAlex person) + 4. UPLOAD the documents to ``orgminer_verified_persons_ude`` (bulk upsert) + 5. CHECKPOINT the organization as done in a small JSON progress file + +Everything runs sequentially: one organization at a time, one graph query at a +time. + +Resumability +------------ +Document IDs are deterministic, so re-running is always safe (documents are +overwritten, never duplicated). The progress file stores only: + +* ``processed_org_doc_ids``: organizations that were fully uploaded. +* ``last_source_uri``: a cursor; every organization sorted before it is done. + +The cursor stops advancing at the first failed organization, so failures are +retried on the next run. + +Usage (from any directory): + python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py + +Requires the INSE and NES Elasticsearch credentials in the service's ``.env`` +file or the environment. ``--dry-run`` verifies and counts without creating the +index, uploading, or touching the progress file. +""" +from __future__ import annotations + +import argparse +import asyncio +import hashlib +import json +import logging +import os +import sys +import time +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable +from contextlib import aclosing +from dataclasses import dataclass, field +from datetime import UTC, datetime +from pathlib import Path +from typing import Any, TypeVar + +import httpx + +SERVICE_DIR = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SERVICE_DIR / "src" / "main")) + +from inse import config # noqa: E402 +from inse.model import ESIndex # noqa: E402 +from inse.orgminer import logic # noqa: E402 +from inse.orgminer.institutions_helper import DEFAULT_INSTITUTION_ID # noqa: E402 + +T = TypeVar("T") +Hit = dict[str, Any] # one Elasticsearch search hit +HierarchyLookup = dict[str, tuple[str, list[str]]] # uri -> (name, path from root) + + +# ============================================================================= +# Configuration +# ============================================================================= + +SOURCE_INDEX = ESIndex.UDE_ORGANIZATION_CONTENT.value +OUTPUT_INDEX = "orgminer_verified_persons_ude" +INSTITUTION_URL = f"https://openalex.org/{DEFAULT_INSTITUTION_ID}" +DEFAULT_PROGRESS_FILE = ( + Path(__file__).resolve().parent / "orgminer_verified_persons_ude_progress.json" +) +PROGRESS_VERSION = 2 + +# Scanning the source index (point-in-time search, paged). +SCAN_PAGE_SIZE = 100 +PIT_KEEP_ALIVE = "10m" +MAX_PIT_RESTARTS = 5 + +# Bulk uploads. +BULK_MAX_DOCS = 250 +BULK_MAX_BYTES = 5 * 1024 * 1024 +MAX_ATTEMPTS = 4 +RETRYABLE_STATUS = {429, 502, 503, 504} + +# Collab-graph queries per organization. Kept at 1: fully sequential. +GRAPH_QUERIES_AT_A_TIME = 1 + +PROGRESS_SAVE_INTERVAL_S = 5.0 +PROGRESS_LOG_INTERVAL_S = 30.0 + +INDEX_MAPPING = { + "dynamic": "strict", + "properties": { + "name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "org_name": {"type": "text", "fields": {"keyword": {"type": "keyword"}}}, + "org_uri": {"type": "keyword"}, + "org_hierarchy_path": {"type": "keyword"}, + "openalex_id": {"type": "keyword"}, + # Kept verbatim in _source; staff dicts vary, so don't index them. + "staff": {"type": "object", "dynamic": False}, + "staff_entries": {"type": "object", "dynamic": False}, + "source_index": {"type": "keyword"}, + "source_org_doc_id": {"type": "keyword"}, + "verification_method": {"type": "keyword"}, + "verification_evidence": { + "type": "nested", + "properties": { + "openalex_id": {"type": "keyword"}, + "collaborator_openalex_id": {"type": "keyword"}, + "shared_work_weight": {"type": "float"}, + }, + }, + "verified_at": {"type": "date"}, + }, +} + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s %(message)s", +) +logger = logging.getLogger("upload_orgminer_verified_persons_ude") + + +# ============================================================================= +# Generic helpers +# ============================================================================= + + +def backoff_delay(attempt: int) -> float: + return min(2.0**attempt, 30.0) + + +async def retry_async( + operation: Callable[[], Awaitable[T]], + *, + description: str, + attempts: int = MAX_ATTEMPTS, +) -> T: + """Run ``operation``; on any exception wait (exponential backoff) and retry.""" + for attempt in range(1, attempts + 1): + try: + return await operation() + except Exception as exc: + if attempt == attempts: + raise + logger.warning( + "%s failed (attempt %d/%d): %s. Retrying.", + description, + attempt, + attempts, + exc, + ) + await asyncio.sleep(backoff_delay(attempt)) + raise AssertionError("unreachable") + + +def require_es_credentials() -> tuple[str, str]: + """Check both clusters are configured; return the INSE (url, api_key).""" + if ( + not config.settings.elasticsearch_url + or not config.settings.elasticsearch_api_key + ): + raise SystemExit( + "NES Elasticsearch credentials are missing. Collab-graph verification " + "needs ELASTICSEARCH_URL and ELASTICSEARCH_API_KEY." + ) + url = config.settings.elasticsearch_inse_url + api_key = config.settings.elasticsearch_inse_api_key + if not url or not api_key: + raise SystemExit( + "INSE Elasticsearch credentials are missing. Set " + "ELASTICSEARCH_INSE_URL and ELASTICSEARCH_INSE_API_KEY in the " + "environment or service/src/main/inse/.env." + ) + return url.rstrip("/"), api_key + + +def make_headers(api_key: str, content_type: str = "application/json") -> dict[str, str]: + return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type} + + +def checkpoint_dir_is_mounted(path: Path) -> bool | None: + """Whether the checkpoint directory is a mount point (relevant in containers). + + Returns ``None`` when the platform doesn't expose mount info (e.g. macOS). + """ + mountinfo = Path("/proc/self/mountinfo") + if not mountinfo.exists(): + return None + try: + directory = str(path.parent.resolve()) + lines = mountinfo.read_text(encoding="utf-8").splitlines() + except OSError: + return None + return any( + len(fields) > 4 and fields[4] == directory + for fields in (line.split() for line in lines) + ) + + +# ============================================================================= +# Run statistics and progress checkpoint +# ============================================================================= + + +@dataclass +class Stats: + scanned: int = 0 + orgs_done: int = 0 + orgs_failed: int = 0 + person_docs: int = 0 + uploaded: int = 0 + doc_errors: int = 0 + started: float = field(default_factory=time.monotonic) + + @property + def has_errors(self) -> bool: + return bool(self.orgs_failed or self.doc_errors) + + def summary(self) -> str: + return ( + f"scanned={self.scanned} orgs_done={self.orgs_done} " + f"orgs_failed={self.orgs_failed} person_docs={self.person_docs} " + f"uploaded={self.uploaded} doc_errors={self.doc_errors} " + f"elapsed={time.monotonic() - self.started:.0f}s" + ) + + +@dataclass +class Progress: + """Checkpoint saved to a JSON file (at most every few seconds, and on exit).""" + + path: Path + persist: bool # False in --dry-run: never write the file + processed_org_ids: set[str] = field(default_factory=set) + last_source_uri: str | None = None + _dirty: bool = False + _last_save: float = 0.0 + + @classmethod + def load(cls, path: Path, *, persist: bool) -> Progress: + progress = cls(path=path, persist=persist) + if not path.exists(): + return progress + try: + state = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SystemExit(f"Could not read progress file {path}: {exc}") from exc + + if ( + state.get("source_index") != SOURCE_INDEX + or state.get("output_index") != OUTPUT_INDEX + ): + raise SystemExit( + f"Progress file {path} belongs to a different source/output index. " + "Choose another --progress-file or move the old file." + ) + progress.processed_org_ids = set(state.get("processed_org_doc_ids", [])) + progress.last_source_uri = state.get("last_source_uri") + return progress + + def reset(self) -> None: + self.processed_org_ids.clear() + self.last_source_uri = None + + def mark_org_done(self, org_doc_id: str) -> None: + self.processed_org_ids.add(org_doc_id) + self._dirty = True + + def advance_cursor(self, uri: str | None) -> None: + if uri and uri != self.last_source_uri: + self.last_source_uri = uri + self._dirty = True + + def save(self, *, force: bool = False) -> None: + if not self.persist or not self._dirty: + return + now = time.monotonic() + if not force and now - self._last_save < PROGRESS_SAVE_INTERVAL_S: + return + state = { + "version": PROGRESS_VERSION, + "source_index": SOURCE_INDEX, + "output_index": OUTPUT_INDEX, + "processed_org_doc_ids": sorted(self.processed_org_ids), + "last_source_uri": self.last_source_uri, + "updated_at": datetime.now(UTC).isoformat(), + } + self.path.parent.mkdir(parents=True, exist_ok=True) + tmp = self.path.with_suffix(self.path.suffix + ".tmp") + tmp.write_text( + json.dumps(state, ensure_ascii=False, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + os.replace(tmp, self.path) # atomic: never leaves a half-written file + self._dirty = False + self._last_save = now + + +# ============================================================================= +# Step 1: READ organizations from the source index +# ============================================================================= + + +class PitExpired(Exception): + """The point-in-time search context is gone and must be reopened.""" + + +def _scan_query(start_uri: str | None) -> dict[str, Any]: + if not start_uri: + return {"match_all": {}} + # Organizations without a URI sort first and can never satisfy a range + # filter, so include them explicitly; already-processed IDs are skipped later. + return { + "bool": { + "should": [ + {"range": {"uri.keyword": {"gte": start_uri}}}, + {"bool": {"must_not": {"exists": {"field": "uri.keyword"}}}}, + ], + "minimum_should_match": 1, + } + } + + +async def _scan_pages( + client: httpx.AsyncClient, + url: str, + headers: dict[str, str], + start_uri: str | None, +) -> AsyncIterator[list[Hit]]: + """Open a point-in-time and yield pages of hits, sorted by URI.""" + response = await client.post( + f"{url}/{SOURCE_INDEX}/_pit", + params={"keep_alive": PIT_KEEP_ALIVE}, + headers=headers, + ) + response.raise_for_status() + pit_id = response.json()["id"] + search_after: list[Any] | None = None + + try: + while True: + payload: dict[str, Any] = { + "size": SCAN_PAGE_SIZE, + "query": _scan_query(start_uri), + "pit": {"id": pit_id, "keep_alive": PIT_KEEP_ALIVE}, + "sort": [ + {"uri.keyword": {"order": "asc", "missing": "_first"}}, + {"_shard_doc": "asc"}, + ], + "track_total_hits": False, + "_source": ["uri", "staff", "name", "org_name", "organization_name"], + } + if search_after is not None: + payload["search_after"] = search_after + + response = await client.post(f"{url}/_search", json=payload, headers=headers) + if response.status_code == 404 and "search_context_missing" in response.text: + raise PitExpired + response.raise_for_status() + + result = response.json() + hits = result.get("hits", {}).get("hits", []) + if not hits: + return + + pit_id = result.get("pit_id", pit_id) + search_after = hits[-1].get("sort") + yield hits + if search_after is None or len(hits) < SCAN_PAGE_SIZE: + return + finally: + try: + await client.request( + "DELETE", f"{url}/_pit", json={"id": pit_id}, headers=headers + ) + except Exception: + logger.warning("Could not close the point-in-time.", exc_info=True) + + +async def scan_organizations( + client: httpx.AsyncClient, + url: str, + headers: dict[str, str], + start_after_uri: str | None, +) -> AsyncIterator[Hit]: + """Yield organizations one by one, in URI order. + + If the point-in-time expires, reopen it and continue from the last URI seen. + Organizations that were already finished are skipped by the caller. + """ + resume_uri = start_after_uri + restarts = 0 + + while True: + try: + async with aclosing(_scan_pages(client, url, headers, resume_uri)) as pages: + async for page in pages: + restarts = 0 + resume_uri = page[-1].get("_source", {}).get("uri") or resume_uri + for hit in page: + yield hit + return + except PitExpired: + restarts += 1 + if restarts > MAX_PIT_RESTARTS: + raise RuntimeError("Point-in-time kept expiring; giving up.") from None + logger.warning( + "Point-in-time expired; reopening from uri=%r (restart %d/%d).", + resume_uri, + restarts, + MAX_PIT_RESTARTS, + ) + + +# ============================================================================= +# Step 3: BUILD one document per (organization, OpenAlex person) +# ============================================================================= + + +def normalize_org_uri(uri: str | None) -> str | None: + if not uri: + return None + normalized = uri.strip().rstrip("/") + if normalized.endswith("/index"): + normalized = normalized[: -len("/index")].rstrip("/") + return normalized or None + + +def build_hierarchy_lookup(hierarchy: Iterable[Any]) -> HierarchyLookup: + """Map normalized organization links to (display name, path from the root).""" + lookup: HierarchyLookup = {} + + def visit(node: Any, ancestors: list[str]) -> None: + name = getattr(node, "name_de", None) or getattr(node, "name_en", None) + path = [*ancestors, name] if name else ancestors + if name: + for link in (getattr(node, "link_de", None), getattr(node, "link_en", None)): + if normalized := normalize_org_uri(link): + lookup[normalized] = (name, path) + for child in getattr(node, "children", None) or []: + visit(child, path) + + for root in hierarchy: + visit(root, []) + return lookup + + +def organization_details( + source: dict[str, Any], hierarchy_lookup: HierarchyLookup +) -> tuple[str, list[str], str | None]: + """Return (org name, hierarchy path, org URI), with fallbacks for the name.""" + org_uri = source.get("uri") + hierarchy_name, hierarchy_path = hierarchy_lookup.get( + normalize_org_uri(org_uri) or "", ("", []) + ) + org_name = ( + source.get("org_name") + or source.get("organization_name") + or source.get("name") + or hierarchy_name + or org_uri + or "Unknown organization" + ) + return str(org_name), hierarchy_path, org_uri + + +def stable_document_id(org_uri: str | None, org_doc_id: str, openalex_id: str) -> str: + """Deterministic ID so re-uploads overwrite instead of duplicating.""" + org_identity = normalize_org_uri(org_uri) or org_doc_id + return hashlib.sha256(f"{org_identity}\0{openalex_id}".encode()).hexdigest() + + +def _canonical(value: Any) -> str: + return json.dumps(value, sort_keys=True, ensure_ascii=False, default=str) + + +def make_person_documents( + source: dict[str, Any], + source_doc_id: str, + verified_entries: list[dict[str, Any]], + hierarchy_lookup: HierarchyLookup, + verified_at: str, +) -> list[tuple[str, Hit]]: + """Turn verified staff entries into [(doc_id, document)], one per OpenAlex person. + + A person may be matched by several staff entries and several collaborators, + so entries and evidence are de-duplicated per person first. + """ + org_name, hierarchy_path, org_uri = organization_details(source, hierarchy_lookup) + + # openalex_id -> {canonical staff json -> staff dict} + staff_by_person: dict[str, dict[str, dict[str, Any]]] = {} + # openalex_id -> {(openalex_id, collaborator_id) -> evidence dict} + evidence_by_person: dict[str, dict[tuple[Any, Any], dict[str, Any]]] = {} + + for entry in verified_entries: + staff = entry["staff"] + staff_key = _canonical(staff) + for openalex_id in entry["openalex_ids"]: + staff_by_person.setdefault(openalex_id, {}).setdefault(staff_key, staff) + seen = evidence_by_person.setdefault(openalex_id, {}) + for evidence in entry["collaboration_evidence"]: + if evidence["openalex_id"] == openalex_id: + key = (evidence["openalex_id"], evidence.get("collaborator_openalex_id")) + seen.setdefault(key, evidence) + + documents: list[tuple[str, Hit]] = [] + for openalex_id, staff_map in staff_by_person.items(): + staff_entries = list(staff_map.values()) + primary_staff = staff_entries[0] + document = { + "name": primary_staff.get("name"), + "org_name": org_name, + "org_uri": org_uri, + "org_hierarchy_path": hierarchy_path, + "openalex_id": openalex_id, + "staff": primary_staff, + "staff_entries": staff_entries, + "source_index": SOURCE_INDEX, + "source_org_doc_id": source_doc_id, + "verification_method": "collab_graph", + "verification_evidence": list(evidence_by_person[openalex_id].values()), + "verified_at": verified_at, + } + doc_id = stable_document_id(org_uri, source_doc_id, openalex_id) + documents.append((doc_id, document)) + return documents + + +# ============================================================================= +# Step 4: UPLOAD documents to the output index +# ============================================================================= + + +async def ensure_output_index( + client: httpx.AsyncClient, url: str, headers: dict[str, str] +) -> None: + """Create the output index with its mapping if it doesn't exist yet.""" + head = await client.head(f"{url}/{OUTPUT_INDEX}", headers=headers) + if head.status_code == 200: + logger.info("Output index %r already exists.", OUTPUT_INDEX) + return + if head.status_code != 404: + head.raise_for_status() + + response = await client.put( + f"{url}/{OUTPUT_INDEX}", json={"mappings": INDEX_MAPPING}, headers=headers + ) + if response.status_code == 400 and "resource_already_exists" in response.text: + logger.info("Output index %r was created concurrently.", OUTPUT_INDEX) + return + response.raise_for_status() + logger.info("Created output index %r.", OUTPUT_INDEX) + + +def _bulk_chunk(doc_id: str, document: Hit) -> str: + action = json.dumps({"index": {"_index": OUTPUT_INDEX, "_id": doc_id}}) + return f"{action}\n{json.dumps(document, ensure_ascii=False)}\n" + + +def _split_batches(items: list[tuple[str, str]]) -> Iterable[list[tuple[str, str]]]: + """Group (doc_id, ndjson) items by document count and payload size.""" + batch: list[tuple[str, str]] = [] + size = 0 + for item in items: + item_size = len(item[1].encode("utf-8")) + if batch and (len(batch) >= BULK_MAX_DOCS or size + item_size > BULK_MAX_BYTES): + yield batch + batch, size = [], 0 + batch.append(item) + size += item_size + if batch: + yield batch + + +async def _post_bulk( + client: httpx.AsyncClient, + url: str, + api_key: str, + batch: list[tuple[str, str]], +) -> dict[str, Any]: + """Send one bulk request, retrying on network errors and retryable statuses.""" + body = "".join(chunk for _, chunk in batch).encode("utf-8") + headers = make_headers(api_key, "application/x-ndjson") + + async def send() -> dict[str, Any]: + response = await client.post(f"{url}/_bulk", content=body, headers=headers) + response.raise_for_status() + return response.json() + + return await retry_async(send, description="Bulk request") + + +async def bulk_index( + client: httpx.AsyncClient, + url: str, + api_key: str, + documents: list[tuple[str, Hit]], +) -> tuple[int, list[tuple[str, str]]]: + """Upsert documents. Return (success count, [(doc_id, error), ...]). + + Items rejected with a retryable status (typically 429 under load) are sent + again with backoff. Everything else that fails is reported as a failure. + """ + pending = [(doc_id, _bulk_chunk(doc_id, doc)) for doc_id, doc in documents] + succeeded = 0 + failures: dict[str, str] = {} + + for attempt in range(1, MAX_ATTEMPTS + 1): + retry: list[tuple[str, str]] = [] + + for batch in _split_batches(pending): + result = await _post_bulk(client, url, api_key, batch) + items = result.get("items", []) + if len(items) != len(batch): + raise RuntimeError( + "Elasticsearch bulk response item count did not match the request." + ) + + for (doc_id, chunk), item in zip(batch, items): + outcome = item.get("index", {}) + status = outcome.get("status", 0) + error = json.dumps(outcome.get("error", outcome), ensure_ascii=False) + if 200 <= status < 300: + succeeded += 1 + failures.pop(doc_id, None) + elif status in RETRYABLE_STATUS: + retry.append((doc_id, chunk)) + failures[doc_id] = error + else: + failures[doc_id] = error + + if not retry: + break + pending = retry + if attempt < MAX_ATTEMPTS: + logger.warning( + "%d bulk items were rejected; retrying (attempt %d/%d).", + len(retry), + attempt, + MAX_ATTEMPTS, + ) + await asyncio.sleep(backoff_delay(attempt)) + + return succeeded, sorted(failures.items()) + + +# ============================================================================= +# Processing a single organization (steps 2-4) +# ============================================================================= + + +@dataclass +class Context: + """Everything `process_organization` needs, bundled in one place.""" + + client: httpx.AsyncClient + url: str + api_key: str + hierarchy_lookup: HierarchyLookup + stats: Stats + dry_run: bool + fail_fast: bool + verified_at: str + + +def staff_of(source: dict[str, Any]) -> list[dict[str, Any]]: + raw = source.get("staff") + if not isinstance(raw, list): + return [] + return [staff for staff in raw if isinstance(staff, dict)] + + +async def process_organization(hit: Hit, ctx: Context) -> bool: + """Verify one organization's staff and upload the result. + + Returns True if the organization is completely done (nothing to retry). + """ + doc_id = str(hit.get("_id") or "") + source = hit.get("_source", {}) + label = source.get("uri") or doc_id + + staff_list = staff_of(source) + if not staff_list: + return True # nothing to verify + + logger.info("Processing organization %s (%d staff entries).", label, len(staff_list)) + + try: + # Step 2: verify staff against the collaboration graph. + verified_entries = await retry_async( + lambda: logic.get_verified_staff_with_collab_graph( + staff_list, + INSTITUTION_URL, + max_concurrent_queries=GRAPH_QUERIES_AT_A_TIME, + ), + description=f"Collab-graph verification for {label}", + ) + + # Step 3: build one document per OpenAlex person. + documents = make_person_documents( + source, doc_id, verified_entries, ctx.hierarchy_lookup, ctx.verified_at + ) + ctx.stats.person_docs += len(documents) + + if ctx.dry_run: + logger.info( + "DRY RUN org=%s verified_staff=%d person_org_docs=%d", + label, + len(verified_entries), + len(documents), + ) + return True + + # Step 4: upload. + uploaded, failures = await bulk_index(ctx.client, ctx.url, ctx.api_key, documents) + ctx.stats.uploaded += uploaded + for failed_id, error in failures: + ctx.stats.doc_errors += 1 + logger.error("Failed to index document %s (org %s): %s", failed_id, label, error) + return not failures + + except Exception: + logger.exception("Failed processing organization %s (_id=%s).", label, doc_id) + if ctx.fail_fast: + raise + return False + + +# ============================================================================= +# Main flow +# ============================================================================= + + +def reset_checkpoint_files(progress_file: Path) -> None: + """Implements --fresh: delete the progress file (and a leftover .tmp file).""" + tmp_file = progress_file.with_suffix(progress_file.suffix + ".tmp") + existed = progress_file.exists() + removed = [] + for path in (progress_file, tmp_file): + try: + path.unlink() + removed.append(str(path)) + except FileNotFoundError: + pass + logger.info( + "--fresh: removed %s. Output index %r is kept and will be updated by upserts.", + removed, + OUTPUT_INDEX, + ) + if existed: + logger.warning( + "--fresh discarded the existing checkpoint. If a saved job command " + "contains --fresh, it restarts from the first organization on every " + "run; remove the flag to resume instead." + ) + + +def prepare_progress(args: argparse.Namespace) -> Progress: + """Load (or reset) the checkpoint according to the CLI flags.""" + if args.fresh: + reset_checkpoint_files(args.progress_file) + + progress = Progress.load(args.progress_file, persist=not args.dry_run) + if args.ignore_progress: + progress.reset() + + logger.info( + "Checkpoint %s: %d finished organizations, resume cursor=%r.", + args.progress_file, + len(progress.processed_org_ids), + progress.last_source_uri, + ) + if not args.dry_run and checkpoint_dir_is_mounted(args.progress_file) is False: + logger.warning( + "Checkpoint directory %s is not a mounted volume, so progress is lost " + "as soon as the container is removed. Set the job's persistent directory " + "to %s.", + args.progress_file.parent, + args.progress_file.parent, + ) + return progress + + +async def run(args: argparse.Namespace) -> int: + # Setup --------------------------------------------------------------- + url, api_key = require_es_credentials() # fail fast, before slow work + headers = make_headers(api_key) + progress = prepare_progress(args) + + hierarchy = await logic.get_hierarchy(INSTITUTION_URL) + hierarchy_lookup = build_hierarchy_lookup(hierarchy) + logger.info("Loaded %d hierarchy URL mappings for UDE.", len(hierarchy_lookup)) + + stats = Stats() + organizations_handled = 0 # for --limit + cursor_blocked = False # set after the first failure; cursor stops moving + last_log = time.monotonic() + + async with httpx.AsyncClient(timeout=httpx.Timeout(90.0)) as client: + if not args.dry_run: + await ensure_output_index(client, url, headers) + + ctx = Context( + client=client, + url=url, + api_key=api_key, + hierarchy_lookup=hierarchy_lookup, + stats=stats, + dry_run=args.dry_run, + fail_fast=args.fail_fast, + verified_at=datetime.now(UTC).isoformat(), + ) + + # Main loop: one organization at a time ----------------------------- + try: + async with aclosing( + scan_organizations(client, url, headers, progress.last_source_uri) + ) as organizations: + async for hit in organizations: + stats.scanned += 1 + org_doc_id = str(hit.get("_id") or "") + org_uri = hit.get("_source", {}).get("uri") + + # Already uploaded in an earlier run. + if org_doc_id in progress.processed_org_ids: + if not cursor_blocked: + progress.advance_cursor(org_uri) + continue + + if args.limit is not None and organizations_handled >= args.limit: + logger.info("Reached --limit=%d.", args.limit) + break + + organizations_handled += 1 + if await process_organization(hit, ctx): + stats.orgs_done += 1 + if not args.dry_run: + progress.mark_org_done(org_doc_id) + if not cursor_blocked: + progress.advance_cursor(org_uri) + else: + stats.orgs_failed += 1 + cursor_blocked = True # retry this one on the next run + + progress.save() + if time.monotonic() - last_log >= PROGRESS_LOG_INTERVAL_S: + logger.info("Progress: %s", stats.summary()) + last_log = time.monotonic() + finally: + progress.save(force=True) + + logger.info("Finished: %s progress_file=%s", stats.summary(), args.progress_file) + return 1 if stats.has_errors else 0 + + +# ============================================================================= +# Command line +# ============================================================================= + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Upload UDE OrgMiner persons verified by the collaboration graph." + ) + parser.add_argument( + "--progress-file", + type=Path, + default=DEFAULT_PROGRESS_FILE, + help=f"JSON checkpoint file (default: {DEFAULT_PROGRESS_FILE})", + ) + parser.add_argument( + "--limit", + type=int, + default=None, + help="Process at most this many not-yet-completed organizations.", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help=( + "Verify and count results without creating the index, uploading, " + "or writing progress. Still reads existing progress unless " + "--ignore-progress is given." + ), + ) + parser.add_argument( + "--ignore-progress", + action="store_true", + help="Start from scratch, ignoring any existing progress file contents.", + ) + parser.add_argument( + "--fresh", + action="store_true", + help=( + "Delete the selected JSON progress checkpoint and start from the " + "first source organization. Existing output-index documents are kept." + ), + ) + parser.add_argument( + "--fail-fast", + action="store_true", + help="Stop at the first organization-level error instead of continuing.", + ) + args = parser.parse_args() + if args.limit is not None and args.limit < 1: + parser.error("--limit must be at least 1.") + return args + + +if __name__ == "__main__": + raise SystemExit(asyncio.run(run(parse_args())))