Spaces:
Running
Running
Deploy eval-entity-registry service
Browse filesFiles changed (2)
2 unmodified lines3456788 unmodified lines17181920212222 unmodified lines4546474849505142 unmodified lines949596979899100101102103104105106107108109630 unmodified lines740741742743744745118 unmodified lines86486586686786886946 unmodified lines91691791891992092192234 unmodified lines9579589599609619629639644 unmodified lines969970971972973974261 unmodified lines123612371238123912401241124212431244124515 unmodified lines126112621263126412651266126737 unmodified lines1305130613071308130913102 unmodified linesimport mathimport reimport unicodedatafrom numbers import Realfrom pathlib import Pathfrom typing import Optional8 unmodified lines# instead of scoping an alias to a config that never calls._SOURCE_SCOPE_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")def seed_collision_key(s: str) -> str:"""Key under which two seed surface forms count as one entity: NFKD +22 unmodified linesif legacy:entry["parents"] = [{"id": legacy, "relationship": "variant", "axis": "size"}]from eval_entity_registry.store.hf_store import get_storefrom eval_entity_registry.store import queries, schemasfrom eval_entity_registry.lib import collision_fold, org_attributionfrom eval_entity_registry.lib.seed_io import WEAK_SCALAR_FIELDS, build_hf_to_dev_from_orgs_yaml42 unmodified linesdef seed(local: bool = typer.Option(False, "--local", help="Write to fixtures/ instead of HF Hub"),seed_dir: str = typer.Option("./seed", "--seed-dir"),prune_stale: bool = typer.Option(False,"--prune-stale/--no-prune-stale",help="Remove reviewed seed entities and seed aliases absent from the current YAML snapshot.",),):"""Load known canonical entities from seed YAML files."""import osif local:os.environ["LOCAL_MODE"] = "true"store = _load_store()seed_path = Path(seed_dir)630 unmodified lines# O(N²) concat-per-row.queries._rebuild_alias_index(store)for table, yaml_file, label, entity_type in seed_specs:table_columns = set(schemas.empty(table).columns)if yaml_file == "__merged_models__":118 unmodified linesif len(cids) == 1}for original_item in items:item = dict(original_item)extra_aliases = item.pop("aliases", []) or []46 unmodified linesglobal_aliases.discard(display_name)alias_specs: list[tuple[str, Optional[str]]] = [(raw, None) for raw in global_aliases if raw]for source_cfg, raw_values in scoped_aliases.items():if not isinstance(source_cfg, str) or not _SOURCE_SCOPE_KEY_RE.match(source_cfg):34 unmodified lines(raw_value, entity_type, _claim_key[2],_prev[0], target_cid, _prev[1], canonical_id))try:queries.add_alias(store, {"raw_value": raw_value,"entity_type": entity_type,"canonical_id": target_cid,4 unmodified lines"confidence": 1.0,"notes": None,}, buffered=True)alias_count += 1except ValueError:# An existing row pointing at a different canonical is a YAML261 unmodified linesremoved_entities = 0removed_aliases = 0if prune_stale:# Only seed-originated rows (strategy == "seed", reviewed entities)# are pruned; sync-created aliases and auto-drafts are never touched.for table, entity_type, yaml_ids, yaml_alias_keys in seed_snapshot:aliases_df = store.table("aliases")seed_mask = (aliases_df["strategy"] == "seed") & (aliases_df["entity_type"] == entity_type)if seed_mask.any():15 unmodified linesentity_df = store.table(table)if len(entity_df) > 0:stale = entity_df["id"].isin(yaml_ids)stale_entities = entity_df[~stale & (entity_df["review_status"] == "reviewed")]# FK guard: an org auto-created from a model's id prefix is not# in the orgs YAML, and pruning it would dangle the model's# org_id; parent_org_id references are kept for the same reason.37 unmodified lines)if removed_entities:typer.echo(f" stale entities removed: {removed_entities}")store.push_to_hub()typer.echo("Seed complete.")2 unmodified lines34567898 unmodified lines18192021222324252627282930313222 unmodified lines5556575859606142 unmodified lines104105106107108109110111112113114115116117118119120121122123630 unmodified lines754755756757758759760761762763118 unmodified lines88288388488588688788888989089189289389489589646 unmodified lines94394494594694794894934 unmodified lines9849859869879889899909919929939949954 unmodified lines1000100110021003100410051006261 unmodified lines12681269127012711272127312741275127612771278127912801281128215 unmodified lines129812991300130113021303130413051306130713081309131013111312131337 unmodified lines135113521353135413551356135713582 unmodified linesimport mathimport reimport unicodedataimport uuidfrom numbers import Realfrom pathlib import Pathfrom typing import Optional8 unmodified lines# instead of scoping an alias to a config that never calls._SOURCE_SCOPE_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")# eval_results columns that hold a canonical id of each entity type; a stale# entity they still point at is kept by --prune-stale._EVAL_RESULTS_FK = {"model": ("model_id",),"benchmark": ("benchmark_id", "parent_benchmark_id"),"metric": ("metric_id",),"harness": ("harness_id",),}def seed_collision_key(s: str) -> str:"""Key under which two seed surface forms count as one entity: NFKD +22 unmodified linesif legacy:entry["parents"] = [{"id": legacy, "relationship": "variant", "axis": "size"}]from eval_entity_registry.store.hf_store import _local_mode, get_storefrom eval_entity_registry.store import queries, schemasfrom eval_entity_registry.lib import collision_fold, org_attributionfrom eval_entity_registry.lib.seed_io import WEAK_SCALAR_FIELDS, build_hf_to_dev_from_orgs_yaml42 unmodified linesdef seed(local: bool = typer.Option(False, "--local", help="Write to fixtures/ instead of HF Hub"),seed_dir: str = typer.Option("./seed", "--seed-dir"),prune_stale: Optional[bool] = typer.Option(None,"--prune-stale/--no-prune-stale",help="Remove entities and seed aliases absent from the current YAML snapshot ""unless a non-seed alias or an eval_results row still references them. ""Default on in local mode, off otherwise.",),):"""Load known canonical entities from seed YAML files."""import osif local:os.environ["LOCAL_MODE"] = "true"if prune_stale is None:prune_stale = _local_mode()store = _load_store()seed_path = Path(seed_dir)630 unmodified lines# O(N²) concat-per-row.queries._rebuild_alias_index(store)# Derived alias ids must not collide with persisted rows (a rejected row# may hold the same key) nor repeat within the run.taken_alias_ids: set[str] = set(store.table("aliases")["id"].dropna().astype(str))for table, yaml_file, label, entity_type in seed_specs:table_columns = set(schemas.empty(table).columns)if yaml_file == "__merged_models__":118 unmodified linesif len(cids) == 1}# A seed row is a function of its YAML entry alone: rows for YAML ids are# dropped and re-inserted whole, so a field removed from YAML cannot linger.yaml_item_ids = {it["id"] for it in items if isinstance(it, dict) and it.get("id")}existing_df = store.table(table)if len(existing_df) > 0:reseeded = existing_df["id"].isin(yaml_item_ids)if reseeded.any():store.set_table(table, existing_df[~reseeded].reset_index(drop=True))for original_item in items:item = dict(original_item)extra_aliases = item.pop("aliases", []) or []46 unmodified linesglobal_aliases.discard(display_name)alias_specs: list[tuple[str, Optional[str]]] = [(raw, None) for raw in sorted(a for a in global_aliases if isinstance(a, str) and a)]for source_cfg, raw_values in scoped_aliases.items():if not isinstance(source_cfg, str) or not _SOURCE_SCOPE_KEY_RE.match(source_cfg):34 unmodified lines(raw_value, entity_type, _claim_key[2],_prev[0], target_cid, _prev[1], canonical_id))alias_id = queries.seed_alias_id(entity_type, raw_value, source_cfg)if alias_id in taken_alias_ids:alias_id = str(uuid.uuid4())try:queries.add_alias(store, {"id": alias_id,"raw_value": raw_value,"entity_type": entity_type,"canonical_id": target_cid,4 unmodified lines"confidence": 1.0,"notes": None,}, buffered=True)taken_alias_ids.add(alias_id)alias_count += 1except ValueError:# An existing row pointing at a different canonical is a YAML261 unmodified linesremoved_entities = 0removed_aliases = 0kept_for_results = 0if prune_stale:# An entity absent from YAML survives only while another writer still# claims it: a non-seed alias, an eval_results row, or (orgs) an FK# from a surviving row. Orgs go last so the FK guard sees pruned models.results_df = store.table("eval_results")for table, entity_type, yaml_ids, yaml_alias_keys in sorted(seed_snapshot, key=lambda t: t[0] == "canonical_orgs"):aliases_df = store.table("aliases")seed_mask = (aliases_df["strategy"] == "seed") & (aliases_df["entity_type"] == entity_type)if seed_mask.any():15 unmodified linesentity_df = store.table(table)if len(entity_df) > 0:stale = entity_df["id"].isin(yaml_ids)stale_entities = entity_df[~stale]referenced_by_results: set[str] = set()if results_df is not None and len(results_df) > 0:for col in _EVAL_RESULTS_FK.get(entity_type, ()):if col in results_df.columns:referenced_by_results |= set(results_df[col].dropna().astype(str))if referenced_by_results:in_results = stale_entities["id"].astype(str).isin(referenced_by_results)kept_for_results += int(in_results.sum())stale_entities = stale_entities[~in_results]# FK guard: an org auto-created from a model's id prefix is not# in the orgs YAML, and pruning it would dangle the model's# org_id; parent_org_id references are kept for the same reason.37 unmodified lines)if removed_entities:typer.echo(f" stale entities removed: {removed_entities}")if kept_for_results:typer.echo(f" stale entities kept (referenced by eval_results): {kept_for_results}")store.push_to_hub()typer.echo("Seed complete.")
543 unmodified lines54454554654754854955055155255334 unmodified lines588589590591592593594543 unmodified linesreturn Nonedef add_alias(store: RegistryStore, data: dict, buffered: bool = False) -> dict:"""Insert an alias row. Raises ValueError when a non-rejected alias alreadyexists for (entity_type, raw_value, source_config). buffered=True defersthe write to flush_pending."""raw_value = data["raw_value"]entity_type = data["entity_type"]source_config = _source_config_key(data.get("source_config"))34 unmodified linesrow = {**data,"source_config": source_config,"id": str(uuid.uuid4()),"created_at": now,"updated_at": now,}543 unmodified lines54454554654754854955055155255355455555655755855956034 unmodified lines595596597598599600601543 unmodified linesreturn Nonedef seed_alias_id(entity_type: str, raw_value: str, source_config) -> str:"""Content-derived alias id over the uniqueness key, so a from-scratch seedis reproducible; the caller must fall back to a random id when it is taken."""key = f"{entity_type}\0{raw_value}\0{_source_config_key(source_config) or ''}"return hashlib.sha256(key.encode("utf-8")).hexdigest()[:32]def add_alias(store: RegistryStore, data: dict, buffered: bool = False) -> dict:"""Insert an alias row. Raises ValueError when a non-rejected alias alreadyexists for (entity_type, raw_value, source_config). buffered=True defersthe write to flush_pending. A caller-supplied `id` is used as-is."""raw_value = data["raw_value"]entity_type = data["entity_type"]source_config = _source_config_key(data.get("source_config"))34 unmodified linesrow = {**data,"source_config": source_config,"id": data.get("id") or str(uuid.uuid4()),"created_at": now,"updated_at": now,}
src/eval_entity_registry/cli.py+57-9
src/eval_entity_registry/store/queries.py+9-2