#!/usr/bin/env python3 """ index.py — idempotent indexing of scored multiplicator rows into Elasticsearch. Target: `multiplicators_v1` on the INSE cluster. The index is admin-created — the standard API key can read/write/update-mapping but NOT create or delete indices, call `_delete_by_query`, or call `_refresh`. Everything below is shaped by those three limits; see README, "Key-permission gotchas". Idempotency: doc _id = "_", and every run first deletes the institution's existing docs via search + bulk-delete-by-id. """ from __future__ import annotations import json import time from datetime import datetime, timezone from typing import Any import httpx from service.scripts.profiling.multipliers.extract import INSE_KEY, INSE_URL, _headers MULTIPLICATORS_INDEX = "multiplicators_v1" NETWORKS_INDEX = "multiplicator_networks_v1" REQUEST_TIMEOUT = 120.0 BULK_CHUNK = 500 MAPPING = { "properties": { "institution_id": {"type": "keyword"}, "cohort_institution_ids": {"type": "keyword"}, "author_id": {"type": "keyword"}, "display_name": { "type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, }, "career_bucket": {"type": "keyword"}, "active_years": {"type": "integer"}, "n_works": {"type": "integer"}, "suspicious_profile": {"type": "boolean"}, "tags": {"type": "keyword"}, "max_sub_score": {"type": "float"}, "sub_scores": { "properties": { "bridger": {"type": "float"}, "mentor": {"type": "float"}, "amplifier": {"type": "float"}, } }, # M3 signal counts "patent_count": {"type": "integer"}, "patent_count_name_only": {"type": "integer"}, # evidence only, never scored "news_mentions": {"type": "integer"}, "cordis_eu_projects": {"type": "integer"}, "industry_coauthor_share_shrunk": {"type": "float"}, "industry_collab_papers": {"type": "integer"}, # Founder-potential model output (founding.py, v2 symmetric models). # Mapped explicitly, not dynamically: a float that happened to be # integral in the first indexed doc would come back as `long` and break # the range queries these fields exist for. The live index also still # carries the unused v1 fields — the key can add mappings, not delete. "founding": { "properties": { # `percentile` is the coach-facing number; `probability_raw` # is a case-control score, NOT a population probability "percentile": {"type": "float"}, "probability_raw": {"type": "float"}, "in_population": {"type": "boolean"}, # conditional timing, one bundle per horizon "p_within_1y_percentile": {"type": "float"}, "p_within_3y_percentile": {"type": "float"}, "p_within_5y_percentile": {"type": "float"}, "p_within_1y_raw": {"type": "float"}, "p_within_3y_raw": {"type": "float"}, "p_within_5y_raw": {"type": "float"}, # sequence point estimate (transformer + lstm cross-check) "predicted_founding_age": {"type": "float"}, "predicted_founding_age_cross_check": {"type": "float"}, "current_career_age": {"type": "integer"}, "years_to_founding": {"type": "float"}, "timing_applicable": {"type": "boolean"}, # provenance "classifier_model": {"type": "keyword"}, "timing_model": {"type": "keyword"}, "timing_cross_check_model": {"type": "keyword"}, "as_of_year": {"type": "integer"}, "patent_source": {"type": "keyword"}, } }, # the exact v2 input record, as coach-facing evidence. `grants` is raw; # `grants_capped` is what the model effectively used. "founding_features": { "properties": { "publications": {"type": "integer"}, "patents": {"type": "integer"}, "grants": {"type": "integer"}, "grants_capped": {"type": "float"}, "first_publication_year": {"type": "integer"}, "first_patent_year": {"type": "integer"}, "first_grant_year": {"type": "integer"}, "industry_collab_papers": {"type": "integer"}, "linked_patents_to_publications": {"type": "integer"}, "publication_research_area": {"type": "keyword"}, "grant_research_area": {"type": "keyword"}, } }, # raw metrics + percentiles kept as dynamic float objects (calibration needs them) "percentiles": {"type": "object", "dynamic": True}, "evidence": { "properties": {"junior_ids": {"type": "keyword"}}, }, "config_hash": {"type": "keyword"}, "computed_at": {"type": "date"}, } } # Visualization docs: nodes/edges are _source-only ("enabled": false) — the # frontend GETs whole docs, never queries into them, and per-field indexing of # ~900 edge objects per doc would be wasted. NETWORK_MAPPING = { "properties": { "institution_id": {"type": "keyword"}, "cohort_institution_ids": {"type": "keyword"}, "author_id": {"type": "keyword"}, "display_name": { "type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, }, "ego": { "properties": { "career_bucket": {"type": "keyword"}, "active_years": {"type": "integer"}, "n_works": {"type": "integer"}, "suspicious_profile": {"type": "boolean"}, "tags": {"type": "keyword"}, "max_sub_score": {"type": "float"}, "sub_scores": { "properties": { "bridger": {"type": "float"}, "mentor": {"type": "float"}, "amplifier": {"type": "float"}, } }, } }, "total_coauthors": {"type": "integer"}, "cohort_coauthors": {"type": "integer"}, "mentee_count": {"type": "integer"}, "shown": {"type": "integer"}, "shown_mentees": {"type": "integer"}, "nodes": {"type": "object", "enabled": False}, "edges": {"type": "object", "enabled": False}, "config_hash": {"type": "keyword"}, "computed_at": {"type": "date"}, } } class MultiplicatorsIndexClient: def __init__( self, base_url: str | None = None, api_key: str | None = None, index: str = MULTIPLICATORS_INDEX, transport: httpx.BaseTransport | None = None, ): self.base_url = (base_url or INSE_URL).rstrip("/") self.api_key = api_key if api_key is not None else INSE_KEY self.index = index self.client = httpx.Client(transport=transport, timeout=REQUEST_TIMEOUT) if not self.base_url or not self.api_key: raise SystemExit("Missing INSE cluster credentials (ELASTICSEARCH_INSE_*).") def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response: return self.client.request( method, f"{self.base_url}/{path.lstrip('/')}", headers=_headers(self.api_key), **kwargs, ) def ensure_mapping(self, mapping: dict[str, Any] | None = None) -> None: """PUT the explicit mapping (additive; safe on every run). Never creates the index.""" response = self._request( "PUT", f"{self.index}/_mapping", json=mapping or MAPPING ) if not response.is_success: raise RuntimeError( f"Mapping update failed ({response.status_code}): {response.text[:500]}" ) def count_for_institution(self, institution_short_id: str) -> int: response = self._request( "POST", f"{self.index}/_count", json={"query": {"term": {"institution_id": institution_short_id}}}, ) response.raise_for_status() return response.json()["count"] def _wait_for_count(self, institution_short_id: str, expected: int, timeout_s: float = 30.0) -> int: """Poll _count until it reaches `expected` or timeout — the key cannot call _refresh, so polling auto-refresh (~1s) is the only verification available.""" deadline = time.time() + timeout_s count = -1 while time.time() < deadline: count = self.count_for_institution(institution_short_id) if count == expected: return count time.sleep(1.0) return count def _collect_ids_for_institution(self, institution_short_id: str) -> list[str]: """All doc _ids for the institution, collected BEFORE any deletes so stale visibility cannot inflate or loop the delete.""" ids: list[str] = [] search_after = None while True: body: dict[str, Any] = { "size": 1000, "_source": False, "query": {"term": {"institution_id": institution_short_id}}, "sort": [{"author_id": {"order": "asc"}}], } if search_after: body["search_after"] = search_after response = self._request("POST", f"{self.index}/_search", json=body) response.raise_for_status() hits = response.json()["hits"]["hits"] if not hits: break ids.extend(h["_id"] for h in hits) search_after = hits[-1]["sort"] return ids def delete_for_institution(self, institution_short_id: str) -> int: """Collect ids, then bulk-delete-by-id (the key 403s on _delete_by_query). Returns the number of docs actually deleted.""" ids = self._collect_ids_for_institution(institution_short_id) deleted = 0 for start in range(0, len(ids), BULK_CHUNK): chunk = ids[start : start + BULK_CHUNK] lines = "".join( json.dumps({"delete": {"_index": self.index, "_id": doc_id}}) + "\n" for doc_id in chunk ) bulk = self.client.post( f"{self.base_url}/_bulk", headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"}, content=lines, ) bulk.raise_for_status() for item in bulk.json()["items"]: result = item.get("delete", {}) if result.get("result") == "deleted": deleted += 1 elif result.get("error"): raise RuntimeError(f"Bulk delete error: {result['error']}") if ids: remaining = self._wait_for_count(institution_short_id, 0) if remaining != 0: raise RuntimeError( f"{remaining} docs for {institution_short_id} still visible " f"after delete (expected 0)" ) return deleted def index_rows( self, institution_short_id: str, cohort_short_ids: list[str], scored_rows: list[dict[str, Any]], ) -> int: """Delete-then-bulk-index all rows for the institution. Returns docs written.""" computed_at = datetime.now(timezone.utc).isoformat() deleted = self.delete_for_institution(institution_short_id) print(f"Deleted {deleted} existing docs for {institution_short_id}") written = 0 for start in range(0, len(scored_rows), BULK_CHUNK): chunk = scored_rows[start : start + BULK_CHUNK] lines = [] for row in chunk: doc = { **row, "institution_id": institution_short_id, "cohort_institution_ids": cohort_short_ids, "computed_at": computed_at, } doc_id = f"{institution_short_id}_{row['author_id']}" lines.append( json.dumps({"index": {"_index": self.index, "_id": doc_id}}) ) lines.append(json.dumps(doc, ensure_ascii=True)) bulk = self.client.post( f"{self.base_url}/_bulk", headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"}, content="\n".join(lines) + "\n", ) bulk.raise_for_status() result = bulk.json() if result.get("errors"): first_error = next( (i["index"].get("error") for i in result["items"] if i.get("index", {}).get("error")), None, ) raise RuntimeError(f"Bulk indexing reported errors, first: {first_error}") written += len(chunk) visible = self._wait_for_count(institution_short_id, written) if visible != written: raise RuntimeError( f"Post-index count mismatch for {institution_short_id}: " f"wrote {written}, index shows {visible} after 30s" ) return written