Core#
The protea.core package contains all domain logic. It has no dependency
on the infrastructure layer: operations receive an open SQLAlchemy session
and an emit callback, but they do not manage connections, queues, or
transactions themselves. This strict boundary makes every operation
independently testable and trivially substitutable.
Axis tuple
protea.core.axis_tuple defines the AxisTuple named-tuple used to
identify a training configuration in the multi-PLM sweep. Each axis
carries the PLM identifier, neighbourhood size k, reranker flag,
feature family set, evaluation set name, propagation mode, and ensemble
strategy. All serialised config keys in Dataset and ExperimentRun
rows use the canonical axis-tuple string form derived from this type.
Axis-tuple shortid: thin shim that prefers the protea-contracts helper.
The canonical implementation lives in protea_contracts.axis_tuple
(shipped by FARM-EXP.1 companion PR on protea-contracts). PROTEA pins
protea-contracts@main in pyproject.toml, so once that PR
merges and we re-lock, the local fallback below disappears via the
try / except ImportError path.
The local fallback is byte-for-byte identical to the upstream helper so the cross-repo shortid contract holds during the brief window where PROTEA is merged before the contracts release that ships the helper.
Formula (mirrors ExperimentSpec.hash() in protea-reranker-lab/src/protea_reranker_lab/experiment.py:108-111):
sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:12]
When the upstream helper is available, this module re-exports it verbatim (same symbol, same digest). Callers should import from here so the swap is invisible:
from protea.core.axis_tuple import axis_tuple_shortid
- protea.core.axis_tuple.CANONICAL_AXIS_KEYS: tuple[str, ...] = ('plm', 'k', 'reranker_spec_id', 'feature_schema_sha', 'eval_set_name', 'eval_set_manifest_sha', 'propagation', 'ensemble_spec')#
Canonical axis-tuple key set. Falls back to the locally-pinned tuple while the upstream contracts release is being rolled out. Order does NOT affect the digest (
json.dumps(..., sort_keys=True)).
- protea.core.axis_tuple.SHORTID_HEX_LEN: int = 12#
Length of the truncated hex digest. Matches the lab convention.
- protea.core.axis_tuple.axis_tuple_shortid(axis_tuple: Mapping[str, Any]) str#
Return the canonical 12-hex shortid for an axis tuple.
- Parameters:
axis_tuple – mapping of axis name to value. Every value must be JSON-encodable by the standard
jsonmodule without a customdefault. Path / UUID / datetime objects must be pre-stringified by the caller (mirrors the lab path’spydantic.model_dump(mode="json")step).- Returns:
12 lowercase hex chars (
[0-9a-f]{12}).- Raises:
TypeError – when a value in
axis_tupleis not JSON-encodable. Surfaced as a hard error so schema drift is caught at the call site rather than producing a silent shortid mismatch.
The function is intentionally pure: same input -> same output, no hidden state, no environment lookup. Order of keys in
axis_tupleis irrelevant (json.dumps(..., sort_keys=True)canonicalises).
Domain types
protea.core.domain.aspect defines the Aspect enum used throughout
the codebase to identify the three GO namespaces: MFO (Molecular Function),
BPO (Biological Process), and CCO (Cellular Component).
GO aspect (namespace) — the three-way partition of the Gene Ontology.
Two encodings circulate in the codebase, both of them load-bearing:
Single-char codes (
"P"/"F"/"C") — the wire format used byGOTerm.aspectin PostgreSQL and thego-basic.obofile itself. Thego_termtable CHECK constraint is on these codes.Three-char CAFA codes (
"BPO"/"MFO"/"CCO") — the format expected bycafaeval(the upstream Fmax / AuPRC evaluator) and surfaced in the UI for human readers.
Until this module landed, both encodings appeared as bare string literals in 30+ places — a textbook Primitive Obsession smell. The enum is the single source of truth; everything else converts at the boundary.
Typical usage:
from protea.core.domain.aspect import Aspect
# Iterate the three aspects in a stable canonical order
for aspect in Aspect:
...
# Convert from a DB row
aspect = Aspect.from_code(row.aspect)
# Hand off to cafaeval
result_dict[aspect.cafa] = ...
- class protea.core.domain.aspect.Aspect(*values)#
Bases:
EnumGene Ontology aspect / namespace.
The three GO sub-ontologies. Iteration order is the canonical PROTEA order (P → F → C), matching the historical
_ASPECTS = ("P", "F", "C")tuples this enum replaces.- BIOLOGICAL_PROCESS = 'P'#
- CELLULAR_COMPONENT = 'C'#
- MOLECULAR_FUNCTION = 'F'#
- property cafa: str#
Three-char CAFA code (
"BPO"/"MFO"/"CCO").Format expected by the upstream
cafaevalpackage and the evaluation results JSON; also the canonical UI label.
- property code: str#
Single-char code (
"P"/"F"/"C").Wire format in PostgreSQL (
go_term.aspectcolumn) and thego-basic.obofile. Use this when reading/writing the DB or comparing against the ORM column.
- protea.core.domain.aspect.reranker_aspect_code(aspect: str | None) int | None#
Map any aspect encoding to the offline lab’s
aspect_codeinteger.Accepts the single-char wire code (
P/F/C, as carried on PROTEA prediction rows) or the three-char CAFA code in any case (MFO/mfo/ …). Returns the lab’s integer encoding (mfo -> 0,bpo -> 1,cco -> 2). Empty or unrecognised input returnsNoneso a downstream numeric column routes it through LightGBM’s native missing-value branch rather than crashing.
Contracts#
The contracts module defines the interfaces that every operation must satisfy and the shared types used across the entire codebase.
Operation is a structural Protocol: any class that exposes a name
string and an execute(session, payload, *, emit) method conforms to it,
without needing to inherit from a base class. ProteaPayload is the
immutable, strictly-typed Pydantic base class for all operation payloads:
strict mode prevents silent type coercion, and frozen configuration prevents
accidental mutation after validation. OperationResult is the return value
of every execute call; its deferred flag tells BaseWorker that
completion will be signalled by child workers rather than immediately.
RetryLaterError is raised when a shared resource (e.g. the GPU) is
occupied; BaseWorker catches it, resets the job to QUEUED, and
re-publishes the message after a configurable delay.
- class protea.core.contracts.operation.Operation(*args, **kwargs)#
Bases:
ProtocolProtocol that every domain operation must satisfy.
Operations are pure domain logic: they receive an open SQLAlchemy session and an
emitcallback for structured event logging, and return anOperationResult. They must not manage sessions or queue connections.descriptionis a short, static, human-readable explanation of what the operation does in general, surfaced in the jobs UI to give the operations history context.summarize_payloadreturns a 1-line dynamic summary of the most informative fields in the payload (e.g. “release 211 ← OBO 2022-07-01”), so each individual job in the history tells its own story. Returning an empty string is acceptable for operations with no useful payload.- description: str#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name: str#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.contracts.operation.OperationResult(result: dict[str, ~typing.Any]=<factory>, progress_current: int | None = None, progress_total: int | None = None, deferred: bool = False, publish_after_commit: list[tuple[str, ~uuid.UUID]]=<factory>, publish_operations: list[tuple[str, dict[str, ~typing.Any]]]=<factory>)#
Bases:
objectReturn value of every Operation.execute() call.
resultis a free-form dict that gets stored inJob.metaand surfaced in the job detail view.progress_current/progress_totalare written back to the Job row so the UI can render a progress bar.deferred: if True, BaseWorker will NOT transition the job to SUCCEEDED. Use this for coordinator operations that delegate work to child jobs; the last child is responsible for marking the parent SUCCEEDED.publish_after_commit: list of (queue_name, job_id) pairs that BaseWorker will publish to RabbitMQ after the DB commit, guaranteeing workers always find the child job row before they try to claim it.- deferred: bool = False#
- progress_current: int | None = None#
- progress_total: int | None = None#
- publish_after_commit: list[tuple[str, UUID]]#
- publish_operations: list[tuple[str, dict[str, Any]]]#
- result: dict[str, Any]#
- exception protea.core.contracts.operation.RetryLaterError(reason: str, delay_seconds: int = 60)#
Bases:
ExceptionRaised by an operation when it cannot run yet but should be retried.
BaseWorker resets the job to QUEUED and the consumer re-publishes the message after
delay_seconds, leaving the GPU free for other work.
- protea.core.contracts.operation.make_safe_emit(raw_emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]#
Wrap a raw EmitFn so failures are logged and never propagate.
The platform-level emit may fail for transient reasons (DB connection lost mid-operation, JobEvent insert conflict, etc.). Operations should not crash because the audit trail hiccupped: the operation’s primary work matters more than the event row. Failures are logged at ERROR with full traceback so they remain visible in observability without breaking the running job.
OperationRegistry is a simple dict-backed mapping from operation name
strings to instances. Workers resolve the correct operation at message
dispatch time; new operations are registered at process startup in
scripts/worker.py without modifying any worker code.
- class protea.core.contracts.registry.OperationRegistry#
Bases:
object
parent_progress exposes the shared
_update_parent_progress helper used by every coordinator
operation (compute_embeddings, predict_go_terms) to advance
the parent job’s progress as child workers finish their batches.
Extracted to its own module in F0 (T0.7) to remove duplicated copies
across coordinators.
Shared helper for child operations that report progress to a parent job.
Used by store_embeddings and store_predictions: each child
batch increments the parent’s progress_current and, if it was
the last batch, transitions the parent from RUNNING to SUCCEEDED.
- protea.core.contracts.parent_progress.REAPED = 'lease_expired'#
The
error_codestale_job_reaperleaves on a job it gave up on.A parent carrying it did not fail. A deferred coordinator clears its lease once its own work is done, and the reaper marks it FAILED when its children stop emitting for longer than its window; the children can and do arrive afterwards. Measured:
b185a6d0was failed this way at exactly six hours, with progress0/7. Any OTHER code on a FAILED parent is a real failure, and the work of its children is not wanted.
- protea.core.contracts.parent_progress.STILL_COUNTS = <sqlalchemy.sql.elements.BooleanClauseList object>#
The same predicate under a public name, for the modules outside this contract that need it.
- protea.core.contracts.parent_progress.in_flight(now: datetime) ColumnElement[bool]#
A coordinator whose children are still in flight, as of
now.RUNNING, whatever its count: a waiting coordinator stays RUNNING until its last child is stored, and the reaper is what decides a RUNNING row is dead.
Or failed by the reaper while its children STILL ARRIVE: its count short of its total AND a job event within the reaper’s own liveness window (
worker.reaper_event_grace_seconds), the signal #1096 judges a waiting coordinator by. Without the time bound a reaped coordinator whose children were discarded stays incomplete forever:b185a6d0(compute_embeddings, reaped on 2026-10-30 at 0 of 7, its seven batches skipped the next day) matched, and would have held the card for good.coalescebecause a count never advanced is NULL, and NULL < total reads as false. Built fromSTILL_COUNTS, so a change in what the reaper’s FAILED means reaches every reader: the card guard (protea.core.operations._card_guard) and the GPU availability endpoint.
- protea.core.contracts.parent_progress.update_parent_progress(session: Session, parent_job_id: UUID, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None], *, event_name: str) None#
Atomically increment parent progress; mark SUCCEEDED if last batch.
Returns silently if the parent has not yet seen all its batches (
progress_current < progress_total) or if no longer RUNNING.The
event_nameis the operation-specific suffix used in theemitcall when the parent transitions to SUCCEEDED, e.g."store_embeddings.parent_succeeded"or"store_predictions.parent_succeeded". The DB-level event row is always written asjob.succeededso downstream consumers see a uniform name regardless of which child closed the parent.
Retry middleware#
protea.core.retry exposes with_retry, a wrapper function used
by BaseWorker to run the execute session against transient
database errors (deadlocks, connection drops, serialisation
failures) and brief network blips. Exponential backoff with jitter;
all knobs (max_attempts, base_delay, max_delay,
jitter_ratio, predicate, on_retry) are bundled in a
RetryPolicy frozen dataclass passed via the policy keyword
argument (T-CONTEXTS, PR #237). BaseWorker instantiates a fixed
policy at call site (RetryPolicy(max_attempts=3, base_delay=1.0,
max_delay=10.0, jitter_ratio=0.3)); there is no global
TuningSettings field for these values. Added as part of F0
(T0.3) of the master plan revision 3.
Generic retry middleware for transient infrastructure errors.
Used by BaseWorker to survive Postgres deadlocks, serialization failures and brief connection interruptions without marking the job as failed. Application errors (validation, missing data) are NOT retried; only transient infrastructure conditions are.
Example:
from protea.core.retry import RetryPolicy, with_retry
def do_work():
...
with_retry(do_work, policy=RetryPolicy(max_attempts=3, base_delay=1.0))
- class protea.core.retry.RetryPolicy(max_attempts: int = 3, base_delay: float = 1.0, max_delay: float = 30.0, jitter_ratio: float = 0.5, predicate: ~collections.abc.Callable[[BaseException], bool] = <function is_retryable>, on_retry: ~collections.abc.Callable[[int, BaseException, float], None] | None = None)#
Bases:
objectBundle of tunable retry knobs consumed by
with_retry().Frozen so a default-constructed policy can sit in a function default safely; callers override individual fields by passing a new
RetryPolicy(...)keyword. Fields:max_attempts: total attempts including the first;< 1is rejected at call time soRetryPolicy(max_attempts=0)does not silently no-op.base_delay/max_delay/jitter_ratio: exponential backoff schedule used between retryable failures.predicate: classifier returningTruefor retryable exceptions; defaults tois_retryable()(DB + transient network errors).on_retry: optional callback fired before each sleep with(attempt, exc, sleep_seconds). Defaults to a structured WARNING log underprotea.retry.
- base_delay: float = 1.0#
- jitter_ratio: float = 0.5#
- max_attempts: int = 3#
- max_delay: float = 30.0#
- on_retry: Callable[[int, BaseException, float], None] | None = None#
- predicate() bool#
Default predicate: retryable DB errors plus transient network errors.
- protea.core.retry.is_retryable(exc: BaseException) bool#
Default predicate: retryable DB errors plus transient network errors.
- protea.core.retry.is_retryable_connection_error(exc: BaseException) bool#
Return True if the exception represents a transient network condition.
These are typically raised by pika or low-level socket layers when the broker is briefly unreachable. The publisher retry loop handles these on the publish side; this predicate exists for the consume side.
- protea.core.retry.is_retryable_db_error(exc: BaseException) bool#
Return True if the exception represents a transient DB condition.
- protea.core.retry.with_retry(fn: ~collections.abc.Callable[[~P], ~protea.core.retry.R], *args: ~typing.~P, policy: ~protea.core.retry.RetryPolicy = RetryPolicy(max_attempts=3, base_delay=1.0, max_delay=30.0, jitter_ratio=0.5, predicate=<function is_retryable>, on_retry=None), **kwargs: ~typing.~P) R#
Run
fn(*args, **kwargs)with exponential backoff and jitter.The callable is invoked up to
policy.max_attemptstimes. After each retryable failure (perpolicy.predicate), the loop sleeps formin(policy.base_delay * 2**(attempt-1), policy.max_delay)seconds, jittered by a random factor in[1 - jitter_ratio, 1 + jitter_ratio].Exceptions that do not match
policy.predicatepropagate immediately. Oncepolicy.max_attemptsretryable failures accumulate, the last exception propagates to the caller.
Operation catalogue#
protea.core.operation_catalog builds the singleton
OperationRegistry that workers consult at message dispatch. The
public function build_operation_registry() instantiates each
operation class and registers it under its canonical name. Adding a
new operation is a one-line edit here plus a new module under
protea/core/operations/.
Single source of truth for the registered operation set.
Both scripts/worker.py and protea/api/app.py build their
OperationRegistry through build_operation_registry() so that the API
and the workers stay in sync about which operations exist and what their
metadata looks like.
- protea.core.operation_catalog.build_operation_registry() OperationRegistry#
Plugin discovery#
protea.core.plugins centralises importlib.metadata.entry_points
discovery for every PROTEA plugin group (protea.backends,
protea.sources, protea.runners). discover_plugins(group)
returns a cached {name: plugin} map and hard-errors with
RuntimeError if a plugin’s name attribute drifts from its
entry-point name. reset_plugin_cache is a test-only seam for
suites that install/uninstall plugins between cases. Added in T2A.5
for backend dispatch and generalised in T2A.8 (PR #240).
Generic entry-point plugin discovery (T2A.5 + T2A.8).
Both backends (T2A.5) and runners (T2A.8) follow the same shape: a
package declares plugins in [tool.poetry.plugins."protea.<group>"]
mapping name = "module:plugin", PROTEA discovers them via
importlib.metadata.entry_points, and a resolver maps a string
identifier to a plugin instance for dispatch.
This module centralises that discovery + cache + name-mismatch hard
error so the backend and runner code paths share one implementation
instead of forking. See protea.core.runners and the
_get_backend_plugins shim in
protea.core.operations.compute_embeddings for the call sites.
- protea.core.plugins.discover_plugins(group: str) dict[str, Any]#
Discover and cache plugins in the given
entry_pointsgroup.Returns a dict keyed by
plugin.name. Each plugin must declare anameclass attribute that matches its entry-point name; mismatches raiseRuntimeErrorat discovery time so the failure surface is a clear “your declaration drifted from your entry_points file” rather than a confusing “Unknown <something>” later on.Discovery happens once per process per group; subsequent calls return the cached map. The cache key is the group string itself, so the same group cannot be discovered twice (which keeps the import-time side effects stable across reload-heavy test runs).
- protea.core.plugins.reset_plugin_cache(group: str | None = None) None#
Drop the cached plugin map for one (or every) group.
Test-only seam: lets unit tests force re-discovery without restarting the process. Passing
group=Noneclears every group; passing a specific name clears only that one. Production callers should not invoke this; the cache is intentionally process-local.
Feature registry
protea.core.features.registry is the central registry that maps
feature-family names to their producer functions. The ALL_FEATURES
constant lists every column the pipeline may populate; adding a column
without wiring a producer here causes a T1.8 invariant failure in the
dataset-export pipeline.
Concrete in-process FeatureRegistry for PROTEA (T2B.1).
The registry is the single point of truth for which feature columns
are computed and which families they belong to. It implements the
protea_contracts.FeatureRegistry ABC and, at import time, is
populated from the canonical
protea_contracts.FEATURE_FAMILIES map so every consumer sees
the same column set and family layout the lab was trained against.
Compute callables are intentionally placeholders in this slice (T2B.1).
T2B.2 of master plan v3.2 §24 wires the existing per-feature compute
helpers (feature_engineering, feature_enricher,
anc2vec_embeddings, pca_cache) into
CanonicalFeatureRegistry.bind_compute() so parquet_export and
_predict_batch can drive feature generation through the registry
instead of the open-coded loops they use today.
Calling a placeholder compute raises NotImplementedError with the
feature name so a premature integration fails loudly rather than
silently emitting empty columns.
A module-level REGISTRY singleton mirrors the cross-repo
contract test pinned in tests.test_feature_contract
(TestRegistryCoversContracts). The test activates automatically
on the presence of this module and pins the
registry-vs-contracts invariant.
- class protea.core.features.registry.CanonicalFeatureRegistry#
Bases:
FeatureRegistryIn-memory
FeatureRegistrypopulated from the contracts.Two membership views co-exist:
Per-feature
Feature.familyscalar (the most specific family, used for metadata / single-tag dispatch).The overlapping
protea_contracts.FEATURE_FAMILIESmap, returned byfamilies()and consulted byselected(). This is what the lab trains against and is the invariant pinned bytests.test_feature_contract.TestRegistryCoversContracts.
Insertion order is preserved so
names()returns features in the order they were registered.- bind_compute(name: str, compute: Any) None#
Replace the placeholder compute for
name.T2B.2 calls this once per feature at module import time to swap the
_placeholder()raiser for the real compute helper. The feature must already be registered.
- families() dict[str, list[str]]#
Return the overlapping family map for currently registered features.
Walks
FEATURE_FAMILIESso the result mirrors the canonical contracts grouping (knnis the union ofknn_distanceandknn_voteplus the std feature, etc.). Only features actually registered are included; the map is empty for a fresh registry.
- get(name: str) Feature#
Return the
Featureregistered undername.- Raises:
KeyError – if
nameis not registered.
- names() list[str]#
All registered feature names, in registration order.
- register(feature: Feature) None#
Add a feature to the registry. Re-registering an existing
nameshould raiseValueErrorso a typo never silently shadows a canonical column.
- selected(active_families: list[str], drop: list[str] | None = None) list[Feature]#
Union the features in every requested family, then apply
drop.Preserves registration order (which mirrors
ALL_FEATURES) so the returned list is deterministic across calls. Unknown family names raiseKeyErrorto mirror the lab’s strict family validation.
- protea.core.features.registry.REGISTRY: CanonicalFeatureRegistry = <protea.core.features.registry.CanonicalFeatureRegistry object>#
Process-wide canonical registry instance. Importing this name activates the cross-repo contract test
tests.test_feature_contract.TestRegistryCoversContractswhich pins the registry-vs-FEATURE_FAMILIESinvariant.
- protea.core.features.registry.get_canonical_registry() CanonicalFeatureRegistry#
Return the process-wide canonical registry, building it on first use.
The registry is rebuilt only after
reset_canonical_registry()(test-only seam). Callers that need to bind real compute helpers (T2B.2) acquire the singleton and callCanonicalFeatureRegistry.bind_compute()per feature.
- protea.core.features.registry.reset_canonical_registry() None#
Drop the cached canonical registry. Test-only seam.
Schema SHA
protea.core.schema_sha_v2 computes a 16-character deterministic
fingerprint of the feature schema version. The hash is embedded in
Dataset.schema_sha and RerankerModel.feature_schema_sha; a
mismatch at inference time indicates that the booster was trained on a
different feature set and must be rejected.
schema_sha_v2 dual-write feature flag (T1.6 of master plan v3).
The protea.infrastructure.orm.models Dataset, RerankerModel, and
ExperimentRun rows carry both the legacy schema_sha /
feature_schema_sha column and the canonical
schema_sha_v2 column added by ADR D10. Until the production
cut-over window, write paths only fill the legacy column; once the
operator flips PROTEA_SCHEMA_SHA_V2_WRITE_ENABLED=true new rows
dual-write both columns.
The flag defaults to false (off) so a normal deploy of this slice
is a pure no-op for the data plane. The accompanying alembic
migration ships the column and a one-shot backfill; production reads
still come off schema_sha until a later slice flips the routers.
Truthy values follow the same convention as
protea.api.auth._authn_required() so operators do not learn two
different env-flag dialects: 1, true, yes, on (case
insensitive). Anything else (including unset) is treated as false.
- protea.core.schema_sha_v2.is_dual_write_enabled() bool#
Return
Truewhenschema_sha_v2should be written on inserts.The check is read-fresh each call so tests can flip the value via
pytest.MonkeyPatch.setenv()without restarting the process and operators can roll the flag forward without redeploying.
- protea.core.schema_sha_v2.maybe_v2(value: str | None) str | None#
Pass-through helper for dual-write call sites.
Returns
valuewhen the flag is on,Noneotherwise. Lets write paths stay terse:schema_sha_v2=maybe_v2(legacy_sha)instead of an inline ternary at every insert site.
JSONB dual-write
protea.core.jsonb_dual_write provides helpers for writing structured
data to both a typed column and a JSONB fallback column in the same
transaction. Used during schema-migration windows where old and new code
may run concurrently against the same database.
Env-flag helper for the T3.1 GOPrediction.predictions_jsonb dual-write.
T3.1 scaffolds the prediction-tuple JSONB dual-write: writers continue
filling the typed prediction columns (go_term_id, distance,
evidence_code) and additionally serialise the same tuple into the
predictions_jsonb blob when the environment opt-in is set. This
keeps the scaffolding inert in production until a human-coordinated
deploy window flips the flag.
Environment variable#
PROTEA_GO_PREDICTION_JSONB_WRITE_ENABLEDTruthy values (
1,true,yes,on; case-insensitive) enable the dual-write. Anything else (unset, empty,0,false…) leaves the writer skipping the JSONB column sopredictions_jsonbstaysNULLon new rows. Default off.
Design notes#
The helper API is intentionally tiny so every writer site can opt in with a single import + one-line call:
from protea.core.jsonb_dual_write import maybe_jsonb
row["predictions_jsonb"] = maybe_jsonb(
[(pred["go_term_id"], pred["distance"], pred.get("evidence_code"))]
)
maybe_jsonb returns None when the flag is off (so the row
dict carries an explicit NULL for SQL) and a compact dict when on.
The compact shape is a single-level dict with two keys:
predictions: a list of{"go_term_id": int, "score": float, "evidence": str | None}records, preserving caller order.count: len(predictions), redundant but useful for cheap GIN filtering and sanity checks (WHERE predictions_jsonb @> '{"count": 5}'etc.).
The list shape lets a single row carry one or more prediction tuples without re-shaping the helper at the T3.2 backfill / T3.3 reader cut-over.
- protea.core.jsonb_dual_write.JSONB_DUAL_WRITE_ENV: str = 'PROTEA_GO_PREDICTION_JSONB_WRITE_ENABLED'#
Environment variable name; exported for tests / docs.
- protea.core.jsonb_dual_write.is_jsonb_dual_write_enabled(env: dict[str, str] | None = None) bool#
Return
Trueiff the env opt-in is set to a truthy value.envdefaults toos.environ; the explicit parameter is a test hook so callers can verify the helper without mutating process state.
- protea.core.jsonb_dual_write.maybe_jsonb(predictions: Sequence[tuple[int, float, str | None]], *, env: dict[str, str] | None = None) dict[str, Any] | None#
Serialise a list of (go_term_id, score, evidence) tuples.
Returns
Nonewhen the dual-write env opt-in is off so the caller can assign the result directly to a row dict / ORM attribute without an explicit guard at every writer site.When the flag is on, returns the compact JSONB shape documented in the module docstring. Empty input still returns a well-formed dict (
{"predictions": [], "count": 0}) so downstream consumers can rely on the keys being present.
Experiment runners#
protea.core.runners adapts the generic plugin discovery to the
protea.runners group. resolve_runner(name) maps an identifier
("knn" / "baseline" / "lightgbm") to a runner plugin
instance implementing the protea_contracts.ExperimentRunner
interface; unknown names raise ValueError listing the discovered
set. PROTEA does not yet dispatch to runners at inference time (the
active KNN + reranker path stays in PredictGOTermsBatchOperation
until F2C of master plan revision 3 hoists the inference core into a
shared package). The adapter exists so GET /v1/runners has a
stable resolver and future code has a one-line entry. Closes T2A.8
(PR #240).
Experiment-runner plugin adapter (T2A.8).
Mirrors the backend-plugin adapter in
protea.core.operations.compute_embeddings: discovers runners via
importlib.metadata.entry_points("protea.runners") and exposes a
resolve_runner() lookup that maps a string identifier (e.g.
"knn" / "baseline" / "lightgbm") to a runner plugin
instance implementing protea_contracts.ExperimentRunner.
The protea-runners package declares the canonical plugin set:
knn: KNN-only baseline (no reranker), evaluates against a frozen dataset for ablation.baseline: predict-by-frequency baseline (most-frequent GO terms in the training set).lightgbm: the v9 / v18 LightGBM reranker, currently trained out-of-tree inprotea-reranker-lab.
PROTEA does not yet dispatch to runners at inference time (the active
KNN + reranker path lives in PredictGOTermsBatchOperation and stays
there until F2C of master plan v3 hoists the inference core into a
package both PROTEA and protea-runners can depend on). The adapter
exists today so:
The plugin registry endpoint (
GET /v1/registry/runners) has a stable resolver under the hood (currently still using its own_discoverfor the API shape; that path is untouched here).Future code that wants a runner instance has a one-line entry:
from protea.core.runners import resolve_runner.The discovery + name-mismatch hard error follows the same pattern as backends, so the lab + plugin authoring workflow is uniform across both groups.
- protea.core.runners.get_runner_plugins() dict[str, Any]#
Return the discovered runner plugins keyed by
plugin.name.Wraps
protea.core.plugins.discover_plugins()so the runner callers do not need to know the entry-point group string; the constant lives here next to the consumers.
- protea.core.runners.resolve_runner(name: str) Any#
Resolve a runner identifier to a plugin instance.
Raises
ValueErrorlisting the discovered runners when the identifier is unknown, so the failure message is actionable. The returned object implementsprotea_contracts.ExperimentRunner.
Utilities#
protea.core.utils provides two shared utilities used across multiple
operations.
utcnow() returns a timezone-aware UTC datetime, avoiding the common
mistake of calling datetime.utcnow() which returns a naive object.
chunks(seq, n) splits any sequence into fixed-size chunks, used by
coordinator operations to partition work into batches.
The previous UniProtHttpMixin (exponential backoff with jitter,
Retry-After header parsing, cursor extraction for paginated UniProt
REST endpoints) was inlined into InsertProteinsOperation and
FetchUniProtMetadataOperation when those operations were rewritten;
the retry/backoff/cursor logic now lives directly in each operation.
- protea.core.utils.chunks(seq: Sequence[Any], n: int) Iterable[Sequence[Any]]#
Yield successive n-sized chunks from seq.
- protea.core.utils.contract_payload(payload: Any) Any#
The payload without the keys the transport added, ready to validate.
base_workerhands every operation{**job.payload, "_job_id": ...}so the operation can find its own job row. That key is delivery metadata, not part of any contract, and no model declares it: pydantic treats a leading underscore as a private attribute, so it CANNOT be declared even if we wanted to.That was invisible while the base payload ignored undeclared keys. It is not invisible now: the contract forbids them, which is the whole point of forbidding them, and a payload validated with
_job_idstill on it raises. Stripping it here keeps the guard pointed at what it is for, which is a key nobody meant to send, rather than at the one the worker sends on purpose.Only underscore-prefixed keys are removed. Anything else the caller did not declare still raises, which is the behaviour worth having: it is how a worker running older code than its dispatcher stops doing the wrong work quietly.
- protea.core.utils.job_id_from_payload(payload: Any) UUID | None#
Resolve the owning Job’s UUID from a worker-enhanced payload.
BaseWorkerinjects the claimed job’s id as_job_idinto every operation payload (base_worker.handle_job). Threading it onto the persisted result row turns an otherwise-orphan artifact (job_id=None) into one with full provenance back to its triggering job: the same disciplineexport_research_datasetalready applies to itsDatasetrow. ReturnsNonewhen the payload carries no_job_id(e.g. a directop.executecall in tests or a non-job-backed dispatch).
- protea.core.utils.utcnow() datetime#
Return the current UTC datetime (timezone-aware).
KNN search#
protea.core.knn_search provides the nearest-neighbour search layer used
during GO term prediction. The single public entry point is search_knn(),
which dispatches to one of two backends based on the backend parameter.
The numpy backend computes exact cosine or L2 distances via matrix multiplication. It requires no additional dependencies and is the default. For cosine distance, query and reference matrices are L2-normalised and the distance is computed as \(D = 1 - \cos(\theta) \in [0, 2]\). This is \(O(NQ)\) and is appropriate for reference sets up to approximately 100 000 proteins when embeddings fit in RAM as float16.
The faiss backend wraps the FAISS library and supports three index
types: Flat (exact), IVFFlat (approximate, Voronoi partitioning),
and HNSW (approximate, hierarchical graph). IVFFlat is recommended
for datasets above 100 000 vectors: it restricts search to the nprobe
nearest Voronoi cells, reducing query time from \(O(N)\) to approximately
\(O(\sqrt{N})\) with negligible recall loss at default settings.
Important
KNN search is never performed at the database layer. pgvector index types (HNSW, IVFFlat) are not used. All search happens in Python after loading reference embeddings into a numpy array. See Predict GO terms in the how-to guides.
K-nearest-neighbour search — thin shim over protea_method.knn_search.
The numpy, FAISS, and torch backends live in the standalone
protea-method library (F2C extraction, 2026-05-07). This module is a
backwards-compatible shim so existing PROTEA call sites that import
from protea.core.knn_search keep working without changes; new
code should import directly from protea_method.knn_search.
PROTEA’s OperationTuning.numpy_query_chunk configuration is
forwarded to the library via the PROTEA_METHOD_NUMPY_QUERY_CHUNK
environment variable on first call, so the chunk-size knob is
preserved without changing call signatures.
Torch backend env vars (pass-through, no PROTEA-side config required):
PROTEA_KNN_DEVICE:"cuda"or"cpu". PROTEA defaults it to"cpu"rather than leaving the library’s"auto", which resolves to CUDA whenever a card is visible. See_default_device_to_cpu.PROTEA_KNN_CHUNK_SIZE: int, default 4096. Number of query rows processed per GPU kernel launch.
- protea.core.knn_search.search_knn(*args, **kwargs)#
Pass through to
protea_method.knn_search.search_knn.Syncs the PROTEA tuning knob into the env var on first call, and pins the device to CPU unless the caller asked for something else.
Feature engineering#
protea.core.feature_engineering enriches each query–reference pair in a
prediction result with sequence-level and phylogenetic signals. These features
are opt-in: they are computed only when compute_alignments=true and/or
compute_taxonomy=true are set in the prediction payload.
Pairwise alignment is computed via the parasail library using the
BLOSUM62 substitution matrix with gap-open/extend penalties of 10/1. Both
global (Needleman–Wunsch) and local (Smith–Waterman) alignments are run for
each pair, producing identity, similarity, raw score, gap percentage, and
alignment length for each. These metrics capture sequence similarity beyond
what the embedding distance alone encodes, which is especially valuable for
distant homologues where embedding geometry may be unreliable.
Taxonomic distance is computed via ete3 and the NCBI taxonomy tree
(local SQLite, downloaded on first use). For each (query, reference) pair
where taxonomy IDs are available from UniProt metadata, PROTEA finds the
lowest common ancestor and computes the edge count through it. Results are
cached with an LRU cache keyed by taxon-ID pair to avoid redundant tree
traversals across a batch.
Feature engineering utilities for functional annotation enrichment.
Provides pairwise alignment metrics (Needleman–Wunsch and Smith–Waterman) via parasail and taxonomic distance computation via ete3 NCBITaxa.
These features complement the embedding-space KNN distance stored in
GOPrediction.distance with sequence-level and phylogenetic signals.
Performance notes:
Alignment is O(m*n) per pair; parasail uses SIMD acceleration.
Taxonomy lookups use an LRU cache over lineage queries (ete3 local SQLite). First call may trigger a DB download if the ete3 database is absent.
- protea.core.feature_engineering.compute_alignment(seq1: str, seq2: str) dict[str, Any]#
Compute both NW and SW alignment metrics in one call.
- protea.core.feature_engineering.compute_nw(seq1: str, seq2: str, *, gap_open: int = 10, gap_extend: int = 1) dict[str, Any]#
Global alignment (Needleman–Wunsch) via parasail/BLOSUM62.
- Returns a dict with keys:
identity_nw, similarity_nw, alignment_score_nw, gaps_pct_nw, alignment_length_nw, length_query, length_ref
- protea.core.feature_engineering.compute_sw(seq1: str, seq2: str, *, gap_open: int = 10, gap_extend: int = 1) dict[str, Any]#
Local alignment (Smith–Waterman) via parasail/BLOSUM62.
- Returns a dict with keys:
identity_sw, similarity_sw, alignment_score_sw, gaps_pct_sw, alignment_length_sw
- protea.core.feature_engineering.compute_taxonomy(t1_raw: Any, t2_raw: Any) dict[str, Any]#
Compute taxonomic distance between two NCBI taxonomy IDs.
- Returns a dict with keys:
taxonomic_lca, taxonomic_distance, taxonomic_common_ancestors, taxonomic_relation
- protea.core.feature_engineering.warmup_taxonomy_db() None#
Pre-initialize the NCBITaxa database.
Call at worker startup so the download (~100 MB on first run) happens before any batch is processed, not mid-flight.
Re-ranker#
protea.core.reranker implements a LightGBM binary classifier that
re-scores GO term predictions using 20 numeric features (embedding distance,
NW/SW alignment metrics, sequence lengths, taxonomic distance and common
ancestors, and 5 aggregate re-ranker signals) plus 3 categorical features
(qualifier, evidence code, taxonomic relation). The full feature list is
documented in train_reranker.
The module provides:
prepare_dataset(df): extracts and coerces feature columns. Numeric columns are coerced witherrors="coerce"(invalid strings becomeNaN); categorical columns are converted to pandascategorydtype, which LightGBM consumes directly without manual label encoding.train(df): stratified positive/negative split with early-stopping on a held-out validation set (default 20 %). Returns aTrainResultwith the Booster, validation metrics (AUC, logloss, precision, recall, F1 at the 0.5 threshold), the best boosting iteration, and gain-based feature importance.predict(model, df): returns probability scores in[0, 1].model_to_string()/model_from_string(): serialization for DB storage in theRerankerModeltable.load_training_tsv(): parses a training data TSV as produced by the/scoring/prediction-sets/{id}/training-data.tsvendpoint.
Note
load_reranker / apply_reranker / infer_active_feature_families
were originally split into a sibling protea.core.reranking module;
they were folded back into protea.core.reranker to remove a naming
trap (reranker vs reranking were impossible to grep apart).
This module is now the single inference-side surface.
LightGBM re-ranker — thin shim over protea_method.reranker.
The pure helpers (feature-column constants, prepare_dataset,
predict, apply_reranker, model_from_string,
fit_embedding_pca, infer_active_feature_families) live in
the standalone protea-method library (F2C extraction,
2026-05-07). This module re-exports them and keeps the
ArtifactStore-bound loader (load_reranker and friends) local
because they touch PROTEA-specific filesystem layout and the
artifact-store abstraction.
Existing call sites that import from protea.core.reranker keep
working without changes; new code should pull pure helpers directly
from protea_method.reranker.
- exception protea.core.reranker.RerankerFeatureDtypeError#
Bases:
ExceptionA booster-expected feature arrived as an un-encodable object column.
Raised by
prepare_reranker_frame()when, after deriving the ad-hoc reranker features, a column the booster lists infeature_name()is stillobjectdtype and is NOT one of the governed categorical columns the scorer label-encodes. Without this guard the failure surfaces deep in LightGBM as the crypticpandas dtypes must be int, float or boolerror (the originalaspect_code: objectincident); raising here names the offending column so an ungoverned-feature gap is loud, not silent.
- protea.core.reranker.apply_reranker(df: pandas.DataFrame, booster: lightgbm.Booster, *, feature_cols: list[str] | None = None) numpy.ndarray#
Score
dfwithboosterand return an aligned array.If
feature_colsis None we use the booster’s ownfeature_name(). Missing columns are filled withnp.nanso LightGBM routes them through its native missing-value branch rather than crashing on KeyError.
- protea.core.reranker.fit_embedding_pca(embeddings: numpy.ndarray, n_components: int = 16, *, max_fit_samples: int = 50000, seed: int = 42) tuple[numpy.ndarray, numpy.ndarray]#
Fit PCA via truncated SVD on a (possibly subsampled) embedding matrix.
Returns
(mean, components)withmeanshape(D,)andcomponentsshape(n_components, D)(both float32). Designed to be called once perEmbeddingConfigpool; subsequent projections are a single matmul.
- protea.core.reranker.infer_active_feature_families(*, compute_alignments: bool, compute_taxonomy: bool, compute_v6_features: bool, compute_lineage_features: bool = False) list[str]#
Map predict-time feature flags onto lab feature families.
Thin PROTEA-side extension of
protea_method.reranker.infer_active_feature_families(): it delegates to the library helper for the base families (knn/annotation_meta/alignment_nw/length/taxonomy_pair/ the v6 bundle) and layers the GO-DAGlineagefamily on top whencompute_lineage_featuresis set.The lineage family is governed here (not in the library) because it is opt-in at serve time via the
compute_lineage_featurespayload flag and must round-trip throughprotea_contracts.compute_feature_schema_sha()so a booster trained with lineage gets a matching live schema sha.Invariant (load-bearing for the FARM-EXP.5 schema-sha guard): with
compute_lineage_features=False(the default) the returned family list is byte-identical to the library output for every align/tax/v6 combination, so the eight existing schema shas (registered trio7fcecf26aa0aetc.) are unchanged. Setting the flag appends exactly thelineagefamily, yielding a new sha (e.g. align+tax+no-v6+lineage ->0810bef8fd4d).
- protea.core.reranker.load_from_bytes(model_bytes: bytes) lightgbm.Booster#
Deserialize a LightGBM booster from raw bytes.
Useful when the caller fetched the booster blob from an external source (artifact store, bind-mounted file, in-memory buffer) and just needs it materialised. The bytes must be the LightGBM text format that
Booster.save_modelwrites.
- protea.core.reranker.load_reranker(artifact_uri: str, *, feature_schema_sha: str, store: ArtifactStore, cache_dir: Path | None = None) lightgbm.Booster#
Fetch (once) and load a LightGBM booster by URI.
The first call materialises the booster blob under
cache_dir/<feature_schema_sha>_<uri_tag>.txt; subsequent calls reuse the on-disk file and an in-process booster cache keyed by the URI.storeis used only when the cached file does not exist;artifact_uriis expected to resolve to a store key but the store implementation chooses whether to parse it (LocalFsArtifactStoreignores the URI and resolves keys from its root; MinIO derives the key from thes3://bucket/keyURI).The on-disk cache is namespaced by
feature_schema_shabecause each sha represents a stable column layout; multiple boosters that share a sha need to disambiguate by URI to avoid the in-process cache returning the first-loaded booster for every cell.
- protea.core.reranker.model_from_string(model_str: str) lightgbm.Booster#
Deserialize a LightGBM booster from its text representation.
- protea.core.reranker.predict(model: lightgbm.Booster, df: pandas.DataFrame, *, categorical_codes: dict[str, list[str]] | None = None) numpy.ndarray#
Score predictions using a trained re-ranker.
Returns an array of scores in [0, 1] where higher = more likely correct. For lambdarank boosters, raw scores are unbounded reals; we apply a sigmoid to calibrate them into the [0, 1] range expected by the downstream CAFA evaluator (which sweeps thresholds from 0 to 1). Binary boosters already emit probabilities, so we leave them alone.
categorical_codesis the per-column ordered string vocabulary the lab used at training time ({column: [val0, val1, ...]}). When provided, each cat column is encoded against this fixed vocabulary so the codes match training; when omitted, falls back topd.factorizeover the inference batch (correct only if the batch happens to contain the same set of values in the same order, usually wrong for small or aspect-filtered batches).
- protea.core.reranker.prepare_dataset(df: pandas.DataFrame) tuple[pandas.DataFrame, pandas.Series]#
Extract feature matrix and label vector from a training DataFrame.
Categorical columns are label-encoded to int64 codes (missing → -1) via
pandas.factorize(). This mirrorsprotea-reranker-lab.reranker.encode_categoricalsso a booster trained either inline here or in the lab can be scored by the samepredicthelper without LightGBM’s “categorical_feature do not match” error firing on cross-instance imports.Returns
(X, y)where X has only the feature columns and y is the binary label.
- protea.core.reranker.prepare_reranker_frame(booster: lightgbm.Booster, df: Any) Any#
Return
dfaugmented with ad-hoc reranker features + object guard.Two responsibilities, both keyed off the booster’s own
feature_name()list:Derive ``aspect_code`` when the booster expects it. The offline lab bakes
aspect_code(mfo -> 0/bpo -> 1/cco -> 2) as a numeric feature, but it is NOT part of the governedprotea_contractsfeature schema, so the genericpredict()/apply_reranker()helpers never build it. Serve/eval prediction rows carry the single-char aspect (P/F/C); we map it throughprotea.core.domain.aspect.reranker_aspect_code()to the SAME integer the booster split on. Absent when the booster does not list it (backward compatible).Guard ungoverned object columns. After the derivation, any booster-expected column still sitting as
objectdtype (and not a governed categorical the scorer label-encodes) raisesRerankerFeatureDtypeErrornaming the column, instead of letting LightGBM emit its opaque bad-dtype error at predict time.
A shallow copy is returned so callers passing a DataFrame slice (e.g. the per-aspect eval path) are never mutated in place.
Parquet export (protea.core.parquet_export)#
protea.core.parquet_export consolidates per-split, per-category
parquet shards produced by the KNN + feature pipeline into the frozen
dataset layout consumed by protea-reranker-lab: exactly
train.parquet, eval.parquet and manifest.json under a single
directory. The manifest follows ManifestV1 (schema version 2)
and records PROTEA’s producer_version + producer_git_sha.
The single public function export_reranker_parquets(...) is shared
by two callers:
training_dump_helpers._dump_frozen_dataset: thin wrapper that uses this helper to emit the dataset alongside a training-data dump.ExportResearchDatasetOperation: stand-alone operation that only materialises and publishes the dataset, without running LightGBM.
When store is provided, the three consolidated files are
additionally uploaded under key_prefix using the ArtifactStore
interface, and the returned dict includes train_uri / eval_uri
/ manifest_uri.
Shared utility that consolidates per-split parquet shards into the
frozen reranker dataset layout consumed by protea-reranker-lab.
The layout is a directory containing exactly three files:
train.parquet concatenated training shards (all splits, all cats) eval.parquet test shards manifest.json metadata compatible with ManifestV1 v2
This module is shared between two producers:
the dump helper(operation) — runs KNN + feature generation for training and optionally dumps the resulting shards.export_research_dataset(operation) — runs the same generation but only to publish the frozen dataset via anArtifactStore(local or MinIO). No LightGBM is trained.
- class protea.core.parquet_export.FamilyProvenance(family: str, state: str, producer: str | None)#
Bases:
NamedTuplePer-family production status recorded in the dataset manifest (ADR-D45).
A feature family is in exactly one of two recorded states for a given export:
produced: a producer ran and wrote real values;producernames it.declared_absent: no producer is wired, so the family’s columns ship asNaN(a missing measurement).producerisNone.
Recording the absence here lets a reader learn it from metadata instead of inferring it from a column of zeros, and lets the shard-write degeneracy check (
_assert_no_degenerate_families()) skip the declared-absent families while still failing loudly on a family that CLAIMS production yet ships a constant column.- family: str#
Alias for field number 0
- producer: str | None#
Alias for field number 2
- state: str#
Alias for field number 1
- protea.core.parquet_export.PRODUCED = 'produced'#
Feature-family provenance states (ADR-D45).
- class protea.core.parquet_export.ParquetExportContext(stage_dir: Path, split_files: dict[str, list[Path]], valid_split_versions: list[tuple[int, int]], test_files: dict[str, Path | None], test_old_v: int, test_new_v: int, name: str, k: int, embedding_config_id: str, ontology_snapshot_id: str, annotation_source: str, store: ArtifactStore | None = None, key_prefix: str = '', producer_version: str | None = None, producer_git_sha: str | None = None, validate_with_contracts: bool = True, feature_family_provenance: tuple[FamilyProvenance, ...] = ())#
Bases:
objectBundle of inputs
export_reranker_parquetsconsumes.Groups the 15 per-call inputs (identity, source shards, publishing options) so the entry-point signature stays under flake8-bugbear’s parameter ceiling. Keep this dataclass authoritative when adding new options.
- annotation_source: str#
- embedding_config_id: str#
- feature_family_provenance: tuple[FamilyProvenance, ...] = ()#
- k: int#
- key_prefix: str = ''#
- name: str#
- ontology_snapshot_id: str#
- producer_git_sha: str | None = None#
- producer_version: str | None = None#
- split_files: dict[str, list[Path]]#
- stage_dir: Path#
- store: ArtifactStore | None = None#
- test_files: dict[str, Path | None]#
- test_new_v: int#
- test_old_v: int#
- valid_split_versions: list[tuple[int, int]]#
- validate_with_contracts: bool = True#
- protea.core.parquet_export.export_reranker_parquets(ctx: ParquetExportContext) dict[str, Any]#
Consolidate per-cat per-split parquet shards into the frozen dataset layout and optionally publish via the configured
ArtifactStore.All inputs live on
ParquetExportContext. Sub-helpers handle shard loading, canonical-column assertion, manifest write, and optional store upload.
Scoring#
protea.core.scoring implements the scoring engine that applies weighted
formulas to GO predictions. A ScoringConfig defines a set of weights for
each feature column (embedding distance, alignment metrics, taxonomy, re-ranker
features). The engine computes a composite score per prediction row and can
stream scored results as TSV or compute CAFA-style metrics (Fmax, AUC-PR)
against an evaluation set.
Scoring engine for GOPrediction rows.
Applies a ScoringConfig
formula to raw prediction signals and returns a normalised [0, 1] confidence score.
The engine is intentionally stateless: every call to compute_score()
is self-contained, which means any ScoringConfig can be applied to an
existing PredictionSet at any time without re-running the KNN search.
Evidence-code weights#
Evidence code quality is resolved through a two-level lookup:
If
config.evidence_weightsis notNone, that dict is checked first.For codes absent from the override (or when no override exists), the module- level
DEFAULT_EVIDENCE_WEIGHTStable is used.Codes unknown to both tables fall back to
DEFAULT_EVIDENCE_WEIGHT_FALLBACK(0.5).
This means a ScoringConfig may carry a partial override — e.g. zeroing
the IEA weight for an experiment-only study — without having to redeclare
every other code. The resolution order ensures backwards compatibility:
configs stored without evidence_weights behave identically to older
configs.
- exception protea.core.scoring.MethodScoreMissing#
Bases:
ValueErrorA
method_scoreconfig met a row that carries no method score.Raised rather than scoring 0.0. A prediction set declaring that its scores are its method’s own, with rows that have none, is a provenance error: the alternative is a cell full of zeros that looks like a method performing badly.
- protea.core.scoring.anc2vec_unit_signal(value: float | None) float | None#
Map an anc2vec cosine in [-1, 1] onto [0, 1] (axis G).
anc2vec_neighbor_cos/anc2vec_neighbor_maxcosare cosine similarities of the candidate term against the neighbour’s annotation centroid, so they live in [-1, 1]. The affine map(x + 1) / 2preserves ordering while landing in the [0, 1] range the weighted average expects. Drops out (None) when the column is absent.
- protea.core.scoring.apply_calibration(score: float, *, aspect: str | None = None, ia_bin: int | None = None, calibration: dict[str, Any] | None = None) float#
Post-score per-(aspect, IA-bin) calibration hook (axis: calibration).
No-op stub with a fixed interface so A-SCORE.2 can drop in isotonic mappings without touching any caller. Returns
scoreunchanged unlesscalibration["enabled"]is set and a populated table is supplied (none ships today). Gated off by default → byte-identical to the legacy score.
- protea.core.scoring.compute_score(pred: dict[str, Any], config: ScoringConfig) float#
Compute a [0, 1] confidence score for a single GOPrediction dict.
Signals are normalised to [0, 1] then weighted-averaged. Signals whose value is
None(feature-engineering flag off at predict time) drop from both numerator and denominator. Returnsround(base_score, 6);FORMULA_METHOD_SCOREshort-circuits the whole average and returns the method’s own number;FORMULA_EVIDENCE_WEIGHTEDmultiplies the average by the resolved evidence weight even when the evidence_weight signal carries weight 0 — so IEA / ND annotations get down-ranked regardless of feature configuration.Composition order (each step is a no-op when its config knob is off, so a config without
paramsscores exactly as before these knobs existed): weighted average, thenx evidence_weightfor the evidence_weighted formula, thenx ia_prior_multiplier(axis E), thenapply_calibration.
- protea.core.scoring.coverage_signal(pred: dict[str, Any]) float | None#
Single principled alignment-coverage signal in [0, 1] (axis A3).
Coverage answers how much of the query is spanned by the aligned region. We prefer the Smith-Waterman local alignment: the Needleman-Wunsch global
alignment_lengthis always ~``max(len_query, len_ref)`` so its coverage saturates near 1 and is uninformative; the local span captures the domain-level match extent that actually discriminates transfers.Definition (
alignment_lengthis the aligned column count,gaps_pctis the gap fraction in [0, 1], not a percentage):ungapped_aligned = alignment_length_sw * (1 - gaps_pct_sw) coverage = clip(ungapped_aligned / length_query, 0, 1)
ungapped_alignedis the number of non-gap aligned columns, i.e. the count of query residues inside the alignment core; dividing by the query length gives the covered fraction. Falls back to the NW fields when the SW fields are absent, and drops out (None) whenlength_queryis missing / non-positive or no alignment length is available.
- protea.core.scoring.evidence_weight(code: str | None, *, overrides: dict[str, float] | None = None) float#
Resolve the [0, 1] quality weight for a GO evidence code or ECO ID.
Resolution order#
Normalise code from ECO ID to GO code via
ECO_TO_CODEif needed.Look up the normalised code in overrides (if provided).
Fall back to
DEFAULT_EVIDENCE_WEIGHTS.If still not found, return
DEFAULT_EVIDENCE_WEIGHT_FALLBACK.
- param code:
A GO evidence code (e.g.
"IEA") or an ECO URI (e.g."ECO:0000501").Nonereturns the fallback weight.- param overrides:
Optional per-config evidence weight table. May be a partial dict; codes not present here are resolved via
DEFAULT_EVIDENCE_WEIGHTS.- rtype:
float in [0, 1].
- protea.core.scoring.ia_prior_multiplier(pred: dict[str, Any], params: dict[str, Any] | None) float#
Multiplicative term-specificity prior in [0, 1] (axis E).
The IA-weighted
f_micro_wobjective rewards specific (high-IA) terms, yet the base composite ignores term specificity entirely. This prior closes that gap: the composite score is multiplied byprior_t ** gammawhereprior_t in (0, 1]is a specificity weight andgamma >= 0tunes its strength (gamma = 0→ multiplier 1 → no effect, a second off-switch).Gated by
params["ia_prior"]["enabled"](default off → returns1.0, preserving the legacy score exactly). Two sources:"frequency"(default): from the term’s corpus countgo_term_frequency.prior = 1 / (1 + log1p(freq))— common terms (large freq) are down-weighted, rare/specific terms keep ~1."ia": from a normalised information-accretion value in [0, 1] supplied on the pred asterm_ia(the caller resolves it from the config-referenced IA file /OntologySnapshot; A-SCORE.2 plug point).prior = clip(term_ia, 0, 1).
When the source field is missing on the pred the prior is
1.0(no penalty) rather than 0, so a partially-featured row is never silently zeroed.
- protea.core.scoring.propagate_ground_truth_to_ancestors(ground_truth: dict[str, set[str]], parent_map: dict[str, set[str]]) dict[str, set[str]]#
Expand each protein’s GO set with every ancestor in
parent_map.Returns a new dict; the input is not modified. Pair with
propagate_scores_to_ancestors()when the downstream metric treats predictions and ground truth symmetrically (e.g. cafaeval-style Fmax).
- protea.core.scoring.propagate_scores_to_ancestors(scored_predictions: list[dict[str, Any]], parent_map: dict[str, set[str]]) list[dict[str, Any]]#
Max-propagate GO scores to ancestors per protein (True Path Rule).
For every (protein, go_id, score) row, ensures every ancestor
aofgo_idinparent_mapalso has score ≥ that row’s score for the same protein. The final score of an ancestor is the max over all its descendants predicted for the protein (including itself if predicted).This mirrors cafaeval’s behaviour: annotating a child implies every ancestor, so predictions must propagate upward before PR metrics.
parent_mapmaps a childgo_id(string) to the set of its direct parentgo_idstrings — typically the union ofis_a+part_ofedges for the relevant ontology snapshot.Returns a new list; the input is not modified. Rows that share a (protein, go_id) collapse to a single row keyed by the max score.
- protea.core.scoring.ref_density_signal(pred: dict[str, Any]) float | None#
Reference-annotation-density signal in (0, 1] (axis F).
ref_annotation_densityis the number of GO annotations carried by the reference (neighbour) protein. A reference with fewer annotations is more specific, so a term transferred from it is a more pointed claim. We squash the raw count with1 / (1 + density): density 0 → 1.0, large density → →0, monotonically decreasing. Drops out (None) when the column is absent.
- protea.core.scoring.score_predictions(predictions: list[dict[str, Any]], config: ScoringConfig) list[dict[str, Any]]#
Add a
scorekey to each prediction dict and return them sorted descending.- Parameters:
predictions – List of raw prediction dicts (same format as accepted by
compute_score()).config – The
ScoringConfigto apply.
- Returns:
A new list with a
scorekey added to each item, sorted by score indescending order. The original list is not modified.
Metrics#
protea.core.metrics implements CAFA-style precision-recall evaluation.
Provides functions for computing Fmax (maximum F-measure over all thresholds),
weighted precision/recall, and coverage for a set of predictions against
ground-truth annotations.
CAFA-style precision-recall metrics for GO term prediction evaluation.
Takes scored GOPrediction rows and EvaluationData (ground truth) and computes Fmax, AUC-PR, and the full precision-recall curve following the CAFA protocol.
CAFA protocol summary#
Evaluate only on proteins present in the ground truth (NK, LK, or PK).
At each score threshold
t:precision(t) = mean over proteins-with-predictions of card(pred & true) / card(pred) recall(t) = mean over ALL ground-truth proteins of card(pred & true) / card(true)
Fmax = max_t(2 * P(t) * R(t) / (P(t) + R(t)))AUC-PR via trapezoidal integration of the PR curve.
Note: This implementation uses exact GO term matching (no DAG propagation). Ancestor propagation is intentionally left for a future iteration.
- class protea.core.metrics.CAFAMetrics(category: str, fmax: float, threshold_at_fmax: float, auc_pr: float, n_ground_truth_proteins: int, n_predicted_proteins: int, n_predictions: int, curve: list[PRPoint] = <factory>)#
Bases:
objectCAFA evaluation results for one (PredictionSet, ScoringConfig, category) triple.
- auc_pr: float#
- category: str#
- fmax: float#
- n_ground_truth_proteins: int#
- n_predicted_proteins: int#
- n_predictions: int#
- summary() dict[str, Any]#
- threshold_at_fmax: float#
- class protea.core.metrics.PRPoint(threshold: 'float', precision: 'float', recall: 'float', f1: 'float')#
Bases:
object- f1: float#
- precision: float#
- recall: float#
- threshold: float#
- protea.core.metrics.compute_cafa_metrics(scored_predictions: list[dict[str, Any]], evaluation_data: EvaluationData, category: str = 'nk') CAFAMetrics#
Compute CAFA Fmax and PR curve.
scored_predictionsmust carryprotein_accession,go_id,scoreper row.categoryselectsnk/lk/pkfrom the evaluation ground truth.
Evidence codes#
protea.core.evidence_codes provides mappings between ECO (Evidence and
Conclusion Ontology) identifiers and GO evidence codes used in GAF files.
Used by the QuickGO annotation loader to resolve ECO IDs to standard
three-letter evidence codes.
GO evidence code utilities.
Provides normalisation from ECO IDs to canonical GO evidence codes and classification of codes as experimental vs. non-experimental.
- Mapping source (canonical ECO → GO code):
https://github.com/evidenceontology/evidenceontology/blob/master/gaf-eco-mapping.txt
Additional ECO IDs used by UniProt GAF (not in the canonical mapping file) are resolved here using the EBI QuickGO ECO term definitions; all are “used in automatic assertion” and therefore map to IEA.
- protea.core.evidence_codes.is_experimental(code: str) bool#
Return True if code (GO or ECO) represents experimental evidence.
Examples:
is_experimental("IDA") # True is_experimental("ECO:0000314") # True (IDA) is_experimental("IEA") # False is_experimental("ECO:0000501") # False (IEA)
- protea.core.evidence_codes.normalize(code: str) str#
Return the canonical GO evidence code for code.
If code is already a GO root evidence code it is returned as-is. ECO IDs are translated via
ECO_TO_CODE. Unknown codes are returned unchanged so that no information is silently discarded.Examples:
normalize("IDA") # → "IDA" normalize("ECO:0000314") # → "IDA" normalize("ECO:0000256") # → "IEA" normalize("UNKNOWN") # → "UNKNOWN"
Evaluation#
protea.core.evaluation implements the CAFA5 evaluation protocol for
computing the ground-truth delta between two annotation snapshots.
The module’s central data structure is EvaluationData, a frozen dataclass
that holds the NK, LK, PK, known, and pk_known annotation dictionaries.
Each dictionary maps a protein accession to a set of GO term IDs.
EvaluationData fields:
nk: delta annotations for No-Knowledge proteins (no prior annotations in any namespace at t0).lk: delta annotations for Limited-Knowledge proteins (had annotations in some namespaces but gained new terms in a previously empty namespace).pk: novel annotations for Partial-Knowledge proteins (gained new terms in a namespace where they already had annotations).pk_known: old experimental annotations for PK proteins in the relevant namespaces; passed as-knowntocafaevalto exclude them from scoring.known: all old experimental annotations flattened across namespaces; available for download via the reference endpoint.
The public entry point is compute_evaluation_data(session,
old_annotation_set_id, new_annotation_set_id, ontology_snapshot_id).
It loads the GO DAG for NOT-propagation, builds a per-namespace annotation
map for both old and new sets, and classifies each (protein, namespace) pair
into NK, LK, or PK. The same protein can appear in multiple categories across
different namespaces simultaneously (e.g., LK in CCO and PK in BPO).
CAFA-style evaluation data computation.
This module computes the ground-truth delta between two AnnotationSets (old → new) following the official CAFA5 evaluation protocol:
Experimental evidence codes only (EXP, IDA, IMP, …)
NOT-qualifier annotations are excluded — including their GO descendants propagated transitively through the is_a / part_of DAG.
Classification is per (protein, namespace), not globally per protein:
- NK — protein had NO experimental annotations in ANY namespace at t0.
All novel terms across all namespaces are ground truth.
- LK — protein had annotations in SOME namespaces at t0, but NOT in
namespace S. Novel terms in S are ground truth for LK.
- PK — protein had annotations in namespace S at t0 AND gained new terms
in S at t1. Novel terms in S are ground truth for PK; old terms in S are the
-knownfile for the CAFA evaluator.Note: the same protein can be LK in one namespace and PK in another simultaneously (e.g. had MFO+BPO at t0, gains CCO → LK in CCO, gains new BPO → PK in BPO).
When the two annotation sets use different OntologySnapshots,
compute_evaluation_data_reconciled implements the CAFA reconciliation
protocol: propagate ancestors under each side’s native DAG, intersect with a
frozen pivot snapshot, then re-propagate is handled by downstream cafaeval
(idempotent under closure semantics). Reference implementation:
anphan0828/democafa_package, utils/ontology.filter_terms_given_obo.
- Output format (matching CAFA evaluator): 2-column TSV, no header.
protein_accession t go_id
- class protea.core.evaluation.EvalContext(old_annotation_set_id: uuid.UUID, new_annotation_set_id: uuid.UUID, ontology_snapshot_id: uuid.UUID)#
Bases:
NamedTupleThe (old, new, snapshot) triple that identifies one evaluation delta.
Bundles the three IDs that travel together through the metrics endpoints (
/scoring/prediction-sets/{id}/metrics) and thecompute_evaluation_data()/_reconciledhelpers, keeping downstream signatures under the master-plan §3 6-param ceiling.- new_annotation_set_id: UUID#
Alias for field number 1
- old_annotation_set_id: UUID#
Alias for field number 0
- ontology_snapshot_id: UUID#
Alias for field number 2
- class protea.core.evaluation.EvaluationData(nk: dict[str, set[str]]=<factory>, lk: dict[str, set[str]]=<factory>, pk: dict[str, set[str]]=<factory>, known: dict[str, set[str]]=<factory>, pk_known: dict[str, set[str]]=<factory>, removed: dict[str, set[str]]=<factory>, projection: dict[str, int] | None=None, binding_dropped: dict[str, int] | None=None)#
Bases:
objectComputed ground-truth delta between two annotation sets.
- binding_dropped: dict[str, int] | None = None#
some 26,000 a window, computed on every build and recorded by nothing until this field. SEPARATE from
projection, whoseNoneclaims “no profile rule ran” while this rule runs on every window.- Type:
Proteins whose ENTIRE F side the binding rule emptied, per side
- property delta_proteins: int#
- known: dict[str, set[str]]#
- property known_terms_count: int#
- lk: dict[str, set[str]]#
- property lk_annotations: int#
- property lk_proteins: int#
- nk: dict[str, set[str]]#
- property nk_annotations: int#
- property nk_proteins: int#
- pk: dict[str, set[str]]#
- property pk_annotations: int#
- pk_known: dict[str, set[str]]#
- property pk_proteins: int#
- projection: dict[str, int] | None = None#
What the projection did while this delta was built, or None under the default profile. BUILD TIME ONLY: the parquet holds the six buckets and nothing else, so a round trip returns None here. The operation stamps it on the
evaluation_setrow, which is where it has to survive.
- removed: dict[str, set[str]]#
- property removed_annotations: int#
- property removed_proteins: int#
- stats() dict#
- class protea.core.evaluation.ReconciledWindow(old_annotation_set_id: uuid.UUID, new_annotation_set_id: uuid.UUID, old_native_snapshot_id: uuid.UUID, new_native_snapshot_id: uuid.UUID, pivot_snapshot_id: uuid.UUID, truth_profile: str = 'as_closed', toi_rule: str = 'pivot_terms', not_codes: str = 'any')#
Bases:
NamedTupleThe five ids a reconciled delta is built from, plus how to build it.
One object for the same reason
EvalContextis one: the five travel together through every lookup, every refusal and every insert, and a signature that took them loose is a signature somebody can call with four. The profile joins them because it decides what the delta IS, not how it is stored: two profiles over the same five ids are two different truths, which is why it is part of the window’s identity in the database too.- new_annotation_set_id: UUID#
Alias for field number 1
- new_native_snapshot_id: UUID#
Alias for field number 3
- not_codes: str#
Alias for field number 7
- old_annotation_set_id: UUID#
Alias for field number 0
- old_native_snapshot_id: UUID#
Alias for field number 2
- pivot_snapshot_id: UUID#
Alias for field number 4
- toi_rule: str#
Alias for field number 6
- truth_profile: str#
Alias for field number 5
- protea.core.evaluation.compute_evaluation_data(session: Session, old_annotation_set_id: UUID, new_annotation_set_id: UUID, ontology_snapshot_id: UUID) EvaluationData#
Compute NK/LK/PK ground truth following the CAFA5 protocol.
Classification is per
(protein, namespace):NK — protein had no experimental annotations in any namespace at
t0.LK — protein had annotations in some namespaces at
t0, but not in namespaceS; gained new terms inS→ those terms are LK ground truth.PK — protein had annotations in namespace
Satt0and gained new terms inS→ those novel terms are PK ground truth; old terms inSare stored inpk_knownfor the cafaeval-knownflag.
The same protein can be simultaneously LK in one namespace and PK in another.
- protea.core.evaluation.compute_evaluation_data_reconciled(session: Session, window: ReconciledWindow) EvaluationData#
CAFA-compliant evaluation delta across mismatched ontology snapshots.
Applies the democafa
filter_terms_given_oboprotocol per side:Load experimental annotations under each set’s native snapshot.
Propagate ancestors under the native DAG (True Path Rule).
Intersect with the pivot snapshot’s term universe.
Step 4 (re-propagate under pivot) is handled by cafaeval downstream, which applies ancestor propagation before scoring —
prop(prop(x)) == prop(x).NOT-qualifier exclusion preserves PROTEA’s True Path Rule contrapositive: NOT terms are propagated to descendants under the native DAG, intersected with pivot, then further propagated under the pivot DAG. The union across both annotation sets is applied to both sides, matching same-snapshot behaviour.
- protea.core.evaluation.deserialize_evaluation_data_from_bytes(blob: bytes) EvaluationData#
Parse parquet bytes (as returned by
ArtifactStore.get) into EvaluationData.
- protea.core.evaluation.groundtruth_key_for(eval_set_id) str#
Storage key under which an EvaluationSet’s ground-truth parquet lives.
- protea.core.evaluation.load_evaluation_data_for_set(session: Session, eval_set) tuple[EvaluationData, UUID]#
Load ground-truth for an EvaluationSet row.
Strict reuse path: if
eval_set.groundtruth_uriis set, deserializes the persisted parquet via the configured ArtifactStore and returns it. If not set, raises — recomputation on-the-fly is intentionally not allowed (see the project’s “no on-the-fly reuse” rule). Usescripts/backfill_evaluation_groundtruth.pyto materialize artifacts for legacy EvaluationSet rows that predate this column.Returns the EvaluationData plus the pivot OntologySnapshot ID — the caller should use the pivot snapshot (not the old set’s) when loading the OBO for cafaeval, since propagated go_ids live in pivot term space.
- protea.core.evaluation.read_groundtruth(session: Session, eval_set) GroundTruthRead#
THE door to a window’s truth parquet. Core and API both come through here.
THERE WERE TWO, WITH TWO DIFFERENT LOCATORS, which is worse than one unverified door. The core recomputed the key from
groundtruth_key_for();api/routers/graph.pysplit the SAVEDgroundtruth_uriand fetched that. So the row’s uri was used by exactly one reader and ignored by the other, and nothing compared them. A test here was called “the only reader” and only looked at the core one.THE LOCATOR IS CHECKED AGAINST THE ROW. The key is derived, and then the stored uri has to end in it. They cannot disagree without one of them being wrong about which object this window’s truth is, and a mismatch is refused rather than resolved by preferring either: preferring the derived key hides a row that points elsewhere, and preferring the uri hides a renamed object.
- protea.core.evaluation.serialize_evaluation_data_to_parquet(data: EvaluationData, dest: Path) Path#
Write
datato a parquet file atdest(creates parent dirs).Returns
destfor convenience. Uses snappy compression and the long layout produced by_eval_data_to_dataframe— kept stable since consumers parse it back withdeserialize_evaluation_data_from_bytes.
Provenance#
protea.core.provenance provides capture_provenance(extra=None),
a side-effect-free runtime snapshot for jobs / experiments / artefacts
to carry an audit trail without DB or network probes. Returns a fresh
dict[str, Any] with auto-keys protea_version (from
importlib.metadata), protea_git_sha (delegates to
parquet_export.resolve_protea_git_sha), python_version,
platform, hostname, and captured_at (ISO-8601 UTC). Any
caller-supplied extra mapping is overlaid last, so callers always
win on key collisions.
Every probe is wrapped: missing distribution metadata, a non-git
checkout, or an absent git binary all degrade to None rather
than raising. Added in T3.11 of master plan v3.2 §24 Fase 4.
Per-run provenance capture (T3.11 of master plan v3.2 §24 Fase 4).
Lightweight utility that snapshots the runtime context of an in-process operation so jobs / experiments / artefacts can carry a small audit trail. Designed to be cheap (no DB, no network) and side-effect-free; safe to call inside operation handlers, lab dumps, or one-shot scripts.
Output schema#
capture_provenance(extra) returns a flat dict[str, Any] with the
following keys (in declaration order):
protea_version— distribution version fromimportlib.metadata;Nonewhen the package metadata is missing (editable install in a worktree withoutpip install -e .etc.).protea_git_sha— current HEAD sha of the PROTEA repo (orNoneoutside a git checkout). Reusesresolve_protea_git_sha()fromparquet_export.python_version— fullsys.versionstring (compiler + build date), useful for reproducibility audits.platform—platform.platform(): OS, kernel, arch.hostname—socket.gethostname(); cheap.libraries— versions of the packages that decide what a vector contains; see_library_versions(). Read from distribution metadata, so nothing heavy is imported.captured_at— ISO8601 UTC timestamp at the call moment.every key in
extrais overlaid last (caller wins on collision).
The helper never raises — every probe wraps a broad except Exception
with a None fallback so a missing metadata package or a non-git
working dir doesn’t poison the manifest.
- protea.core.provenance.capture_provenance(extra: dict[str, Any] | None = None) dict[str, Any]#
Snapshot runtime provenance into a flat
dict.The optional
extramapping is overlaid last so callers can pin domain-specific tags (run_id,embedding_config_id,role) alongside the generic environment fields without losing any of the automatic probes when their key happens to coincide.Always safe to call: every system probe wraps
Exceptionand falls back toNoneso a missing distribution metadata or a non-git working dir never breaks the caller.
- protea.core.provenance.stamp_library_provenance(emit: Any) None#
Record, through
emit, the library versions AND the revision that runs.Called by the worker immediately before an operation executes. The job row records WHAT ran; this says WHICH CODE and WITH WHICH BUILDS, which together are what decide the numbers.
Emitted from the worker and never from the server, because the two machines run different
torchbuilds by design: only the process that executes an operation can say which build produced a given vector.WHY THE REVISION BELONGS HERE AND NOT ONLY IN THE GUARD. This function used to emit the libraries alone, and said so on the grounds that “the revision guard records WHICH CODE”. The guard does – to the journal, at the moment a worker STARTS. Nothing of it reaches the job. So a worker replaced between two batches of one job writes rows under the same job id, with the same library versions, from different code, and the record cannot tell them apart.
That is not hypothetical on this deployment. The compute node syncs itself to the declared revision on a 3-minute timer, and its in-flight guard only defers while a batch is actually mid-operation: between batches the gap is 0,16 s in a 3,2 s cycle, so a tick lands in it with probability around 5% and therefore within about an hour. On 2026-10-28 that was the reason the declaration could not be merged while job
cbaba8bbwas alive – 545.488 of its 684.048 vectors were still to compute – and had it been merged, the mixed provenance would have left no trace anywhere.code_revisionand notresolve_protea_git_sha: the first is stamped at IMPORT, so it names the code this process actually loaded rather than whatever the tree says when asked, and it returns a bare sha only when that sha is genuinely identifying. It is also free, where the other shells out togit rev-parse– whichcapture_provenancewas doing on every batch of every run and then discarding, 10.689 subprocesses on this job alone. Taking the libraries straight from the probe removes that.
- protea.core.provenance.where_it_runs() dict[str, Any]#
The machine, the interpreter and the revision this process runs, for
job.started.ADR-D55’s receipt records, for every job, where it ran: the checklist refuses a heavy step on the server, and a worker replaced between two jobs must not leave them indistinguishable. All three answers are free: the hostname from the socket module, the interpreter from
platform, and the revision stamped at import, which names the code this process loaded rather than whatever the tree says when asked. Nothing here shells out.
Operations#
PROTEA ships a curated set of registered operation instances at worker
startup via protea.core.operation_catalog.build_operation_registry,
which is the authoritative list (read the function body for the live
count).
The catalog splits into job-backed entries (reachable through
POST /jobs) and ephemeral consumers (dispatched internally by the
compute_embeddings and predict_go_terms coordinators; see
Operations for that taxonomy). Each operation is a
class that implements the Operation protocol: a name string and
an execute method. Operations are stateless with respect to
infrastructure: they receive a session and emit structured events, but
do not open connections or manage transactions. The job-backed entries
are documented below; the four ephemeral siblings
(compute_embeddings_batch, store_embeddings,
predict_go_terms_batch, store_predictions) live in
Operations.
- ping
Smoke-test operation. Returns immediately with a success result. Used to verify end-to-end connectivity between the API, RabbitMQ, and worker processes.
- class protea.core.operations.ping.PingOperation(*args, **kwargs)#
Bases:
Operation- description: str = 'Smoke-test operation that emits two events and returns immediately.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name: str = 'ping'#
- summarize_payload(payload: dict[str, Any]) str#
- insert_proteins
Fetches protein sequences from the UniProt REST API using cursor-based FASTA streaming. Sequences are deduplicated by MD5 hash before upsert; proteins are upserted by accession. Exponential backoff with jitter and
Retry-Afterheader handling are implemented inline in the operation. Isoforms are parsed and stored separately, sharing the canonical sequence where the amino-acid string is identical.
- class protea.core.operations.insert_proteins.InsertProteinsOperation#
Bases:
OperationFetches protein sequences from UniProt (FASTA) and upserts them into the DB.
Reads either a release directory’s gzipped flat files or the search endpoint by cursor, depending on the payload;
_stream_fasta()documents which to use. Both paths share exponential backoff with jitter and MD5-based sequence deduplication. Many proteins can share one Sequence row. Isoforms (<canonical>-<n>) are stored as separate Protein rows grouped bycanonical_accession.The whole run is one transaction: nothing is visible until it commits, and a failure leaves no partial universe.
- description: str = 'Fetch protein sequences from UniProt (FASTA, from release files or cursor-paginated) and upsert Protein + Sequence rows; isoforms are stored grouped by canonical accession.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name: str = 'insert_proteins'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.insert_proteins.InsertProteinsPayload(*, search_criteria: str, release_fasta_urls: list[str] = [], page_size: Annotated[int, Gt(gt=0)] = 500, total_limit: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0)])] | None = None, timeout_seconds: Annotated[int, Gt(gt=0)] = 60, include_isoforms: bool = True, compressed: bool = False, max_retries: Annotated[int, Gt(gt=0)] = 6, backoff_base_seconds: Annotated[float, Ge(ge=0.0)] = 0.8, backoff_max_seconds: Annotated[float, Ge(ge=0.0)] = 20.0, jitter_seconds: Annotated[float, Ge(ge=0.0)] = 0.4, user_agent: str = 'PROTEA/insert_proteins (contact: you@example.org)')#
Bases:
ProteaPayload- backoff_base_seconds: NonNegativeFloat#
- backoff_max_seconds: NonNegativeFloat#
- compressed: bool#
- include_isoforms: bool#
- jitter_seconds: NonNegativeFloat#
- max_retries: PositiveInt#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_http_urls(v: list[str]) list[str]#
- classmethod must_be_non_empty(v: str) str#
- page_size: PositiveInt#
- release_fasta_urls: list[str]#
Gzipped FASTA files from a UniProt release directory to read instead of walking the search endpoint by cursor. Empty means paginate. See
InsertProteinsOperation._stream_fasta()for when each path is the right one.
- search_criteria: str#
The UniProt query to fetch. When
release_fasta_urlsis set it is not used to fetch anything, but it is still required and still recorded: it states which query the named files are being asserted to be equivalent to, so the declaration is readable without opening the URLs.
- timeout_seconds: PositiveInt#
- total_limit: PositiveInt | None#
- user_agent: str#
- fetch_uniprot_metadata
Downloads TSV functional annotation data from UniProt and upserts
ProteinUniProtMetadatarows keyed by canonical accession. Fields include functional description, EC numbers, pathway membership, and kinetics. Isoforms inherit metadata through thecanonical_accessionjoin; no duplicate rows are created.
- class protea.core.operations.fetch_uniprot_metadata.FetchUniProtMetadataOperation#
Bases:
objectFetches functional annotations from UniProt (TSV) and upserts ProteinUniProtMetadata rows.
One metadata row is stored per canonical accession. Isoforms share the same metadata record. Optionally updates core Protein fields (reviewed, organism, gene_name, length) if they are missing. Uses the same cursor-based pagination and backoff strategy as InsertProteinsOperation.
- FIELD_MAP: dict[str, str] = {'absorption': 'Absorption', 'active_site': 'Active site', 'activity_regulation': 'Activity regulation', 'binding_site': 'Binding site', 'catalytic_activity': 'Catalytic activity', 'cofactor': 'Cofactor', 'dna_binding': 'DNA binding', 'ec_number': 'EC number', 'features': 'Features', 'function_cc': 'Function [CC]', 'keywords': 'Keywords', 'kinetics': 'Kinetics', 'pathway': 'Pathway', 'ph_dependence': 'pH dependence', 'redox_potential': 'Redox potential', 'rhea_id': 'Rhea ID', 'site': 'Site', 'temperature_dependence': 'Temperature dependence'}#
- UNIPROT_FIELDS: list[str] = ['accession', 'reviewed', 'id', 'protein_name', 'gene_names', 'organism_name', 'length', 'absorption', 'ft_act_site', 'ft_binding', 'cc_catalytic_activity', 'cc_cofactor', 'ft_dna_bind', 'ec', 'cc_activity_regulation', 'cc_function', 'cc_pathway', 'kinetics', 'ph_dependence', 'redox_potential', 'rhea', 'ft_site', 'temp_dependence', 'keyword', 'feature_count']#
- description = 'Fetch functional annotations (TSV) from UniProt and upsert ProteinUniProtMetadata rows keyed by canonical accession.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'fetch_uniprot_metadata'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.fetch_uniprot_metadata.FetchUniProtMetadataPayload(*, search_criteria: str, page_size: Annotated[int, Gt(gt=0)] = 500, total_limit: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0)])] | None = None, timeout_seconds: Annotated[int, Gt(gt=0)] = 60, compressed: bool = True, max_retries: Annotated[int, Gt(gt=0)] = 6, backoff_base_seconds: Annotated[float, Ge(ge=0.0)] = 0.8, backoff_max_seconds: Annotated[float, Ge(ge=0.0)] = 20.0, jitter_seconds: Annotated[float, Ge(ge=0.0)] = 0.4, user_agent: str = 'PROTEA/fetch_uniprot_metadata (contact: you@example.org)', commit_every_page: bool = True, update_protein_core: bool = True)#
Bases:
ProteaPayload- backoff_base_seconds: NonNegativeFloat#
- backoff_max_seconds: NonNegativeFloat#
- commit_every_page: bool#
- compressed: bool#
- jitter_seconds: NonNegativeFloat#
- max_retries: PositiveInt#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- page_size: PositiveInt#
- search_criteria: str#
- timeout_seconds: PositiveInt#
- total_limit: PositiveInt | None#
- update_protein_core: bool#
- user_agent: str#
- load_ontology_snapshot
Downloads a GO OBO file and populates
OntologySnapshot,GOTerm, andGOTermRelationshiprows. Theobo_versionfield carries a unique constraint so that re-importing the same release is idempotent. If a snapshot already exists but its relationships are missing, they are backfilled automatically.
- class protea.core.operations.load_ontology_snapshot.LoadOntologySnapshotOperation#
Bases:
objectDownloads a go.obo file and upserts an OntologySnapshot + GOTerm rows.
The
data-version:header of the OBO file is used as the canonical version identifier (e.g.releases/2024-01-17). If a snapshot with that version already exists, the operation is a no-op and returns the existing snapshot id, making it safe to re-run.GO term aspect is mapped from the OBO
namespacefield:biological_process→ P,molecular_function→ F,cellular_component→ C.- description = 'Download a GO OBO file and persist it as an OntologySnapshot with its GOTerm + GOTermRelationship rows; idempotent on the OBO data-version.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'load_ontology_snapshot'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.load_ontology_snapshot.LoadOntologySnapshotPayload(*, obo_url: str, timeout_seconds: int = 120, force_relationships: bool = False)#
Bases:
ProteaPayload- force_relationships: bool#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- obo_url: str#
- timeout_seconds: int#
- extract_goa_universe
Scans one GOA release and makes every accession it admits under the declared tiers exist in
proteinas an accession-only row, so the annotation loader has nothing left to skip. Opens no connection but the one that fetches the GAF. See ADR-D49.
Grow the protein universe from one GAF, without asking anybody anything.
THE DEFECT THIS CLOSES. load_goa_annotations stores an annotation only when
its accession is already in protein, and silently skips the rest – it has to,
because protein_go_annotation.protein_accession is a FOREIGN KEY. For the
whole clean campaign that filter meant “reviewed only”, a scope nobody had
written down: it was a search_criteria in one insert_proteins payload from
2026-09-15. Measured 2026-10-05, UniProtKB with the thirteen lafa evidence codes:
93.526 reviewed against 149.774 in total, so roughly 56.000 proteins carrying
curated experimental labels never reached the corpus, and the count of how many
were dropped lived only in a job event.
WHY THE UNIVERSE COMES FROM THE GAF AND NOT FROM A UNIPROT QUERY. A query describes today. The campaign spans 2016 to 2026, and a protein that held experimental evidence in 2018 and lost it, or left UniProt entirely, does not appear in today’s answer – yet it took part in the deltas the model learns from. Deriving the universe from each GAF as it loads is the only definition that moves with the series. Measured over three releases (160, 194, 235): the union is 196.164 accessions, 46.390 more than today’s query returns, and the curve was still climbing, so even that is a floor.
WHY THIS OPERATION TOUCHES NO NETWORK BUT THE FILE. It used to. ensure_goa_universe
scanned the GAF and then, in the same job, fetched the missing sequences from
UniProt, backfilled audit dates and resolved merged accessions. That put a remote
service in the middle of a pass that has to run 75 times, and it repeated the same
work every time: an accession UniProt no longer serves was asked for again at every
release that annotates it, measured at 34% of the requests in the ten passes that
ran that way.
Splitting it is not a tidier arrangement of the same work, it is less work. The
sequences are needed ONCE, at the end, over the union of all 75 releases, and
protein.sequence_id is nullable precisely so a row can exist before its
sequence does. So this operation inserts accessions and nothing else, and
protea.core.operations.resolve_protein_sequences runs once when the series
is finished. A release pass is then a pure function of a cached file, which is
also what makes it safe to re-run: no state anywhere else can have moved.
What phase 2 needs is exactly what this writes. load_goa_annotations gates on
select(Protein.accession), so an accession-only row admits every annotation
the GAF carries for it. Annotations for a protein whose sequence never arrives are
kept, not dropped: a protein deleted from UniProt still took part in the deltas,
and the queries that need a sequence filter on sequence_id IS NOT NULL.
NOT-QUALIFIED ROWS COUNT. A NOT annotation is curated knowledge and a scarce kind
– negative results are hard to publish – and the evaluation already uses it:
_reconcile_not_side propagates NOT to descendants and subtracts them. So a
protein whose only reliable annotation is a NOT belongs in the universe. The
donor policy still excludes NOT rows when picking neighbours, which is a
different question and stays as it is.
WHICH ACCESSIONS, EXACTLY. The criterion is four tiers and lives in the payload;
protea.core.operations._universe_sources holds the evidence sets, the
measurements behind each inclusion and exclusion, and the Swiss-Prot-from-GAF
rule. ADR-D49 is the decision record.
- class protea.core.operations.extract_goa_universe.ExtractGoaUniverseOperation(*args, **kwargs)#
Bases:
OperationMake every accession a GAF admits exist in
protein, accession only.Runs BEFORE
load_goa_annotationsfor the same release, on the same cached file. One pass over one GAF costs roughly 4,4 minutes of CPU on top of the thirty-five a release already takes, and nothing in it waits on a remote service, so a release pass is as fast as the disk.Runs on
protea.jobs.- description: str = "Scan one GOA release and make every accession it admits under the declared tiers exist in the protein table, as an accession-only row. Runs before load_goa_annotations for the same release, because protein_go_annotation.protein_accession is a foreign key and the loader can only skip what is not there. Touches no network but the GAF: sequences, audit dates and merged accessions are resolve_protein_sequences' job, once, at the end of the series. NOT-qualified rows count: a NOT is curated knowledge and the evaluation propagates it."#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name: str = 'extract_goa_universe'#
- payload_model#
alias of
ExtractGoaUniversePayload
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.extract_goa_universe.ExtractGoaUniversePayload(*, gaf_url: str, release: Annotated[int, Gt(gt=0)], timeout_seconds: Annotated[int, Gt(gt=0)] = 120, dry_run: bool = False, admit: list[str] = ['truth', 'curated_inference', 'swissprot_of_release'])#
Bases:
ProteaPayload- admit: list[str]#
it is the decision that defines the corpus, and keeping it in a module constant is precisely how a
reviewed:truesearch criterion fixed the scope of a whole campaign on 2026-09-15 without anybody declaring it. Here it is on the job row, queryable after the fact.truthThe thirteen LAFA codes. The only tier that makes a protein an evaluation TARGET. Measured on GOA 156: 117,136 accessions.
curated_inferenceISS ISO ISA ISM IGC RCA NAS IKR IRD– a curator’s judgement about THIS protein, never truth. Measured on GOA 156: 62,363 proteins enter by these and nothing else.swissprot_of_releaseThe entry was reviewed AT THIS RELEASE, read from the entry name the GAF itself carries. See
protea.core.operations._universe_sources.is_swissprot_entry()for the measurement: 527,149 on GOA 156, zero false positives.
WHAT IS NOT HERE, and why the list is an enumeration rather than a complement: the previous version admitted “anything that is not IEA”, which let in
IBA(58% of the corpus, a mechanically propagated family consensus) andND(a curator recording that they found NOTHING, on root terms whose Information Accretion is zero). A complement admits whatever GO invents next without anybody deciding; an enumeration does not, and an unknown code is counted and reported instead.- Type:
WHICH TIERS ADMIT A PROTEIN. This lives in the PAYLOAD deliberately
- dry_run: bool#
- gaf_url: str#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- release: Annotated[int, Field(gt=0)]#
WHICH RELEASE THIS IS, stored on every row the pass inserts as
protein.first_admitted_release. Required rather than parsed out ofgaf_url, because a number read from a URL is a guess about a filename convention, and this one is written into the corpus.
- classmethod tiers_must_be_known_and_nonempty(v: list[str]) list[str]#
- timeout_seconds: Annotated[int, Field(gt=0)]#
- resolve_protein_sequences
Fetches sequences, audit dates and merged-accession links from UniProt for every row that lacks them. Runs once, after the GAF series, because the sequences are needed over the union of the releases and not per release.
Give the universe its sequences, its audit dates and its merged accessions.
WHY THIS IS ITS OWN OPERATION, AND WHY IT RUNS ONCE. extract_goa_universe
walks a GAF and writes accessions; nothing it writes needs UniProt. The sequences
do, and they are needed ONCE, over the union of all 75 releases, after the series
is finished. Doing it per release instead – which is what ensure_goa_universe
did – asked UniProt again at every release that annotates the same protein, and
asked again for accessions UniProt does not serve at all: measured at 34% of the
requests across the ten passes that ran that way.
So the shape here is the one 8 of the platform’s 9 networked operations already
have: one declared source, one pass over the population, transport in the
protea_sources plugin. protea.core.operations._universe_http – a private
115-line copy of the plugin’s retry logic, down to the same {429, 500, 502, 503,
504} set and the same Retry-After handling – is gone with it.
WHAT “THE POPULATION” IS, and why it is a query rather than a payload. Every
protein row with no sequence_id. That is not a scope somebody chose, it is
the definition of what is missing, read from the table at the moment the job runs.
A list of accessions in a payload would be a hypothesis about the state of the
database frozen at submission time, and the campaign has already been bitten once
by a scope that lived in a payload (search_criteria: reviewed:true, 2026-09-15).
THREE PASSES, AND THEY ARE NOT THE SAME QUESTION.
Sequences. /uniprotkb/accessions in batches of a thousand, TSV, asking for
the sequence and the three audit dates in one request. An accession UniProt no
longer serves is simply absent from the answer – a well-formed but unknown
identifier gives 200 and is omitted, while a MALFORMED one gives 400 for the whole
batch, which is why the grammar gate runs first. So fetched is smaller than
candidates by exactly the number of proteins that existed when their GAF was
published and do not exist now. That difference is the quantity the old silent
filter threw away.
Merges. See SECONDARY ACCESSIONS below. Asked of whatever still has no sequence
after the first pass, and asked of the DATABASE rather than of arithmetic:
candidates minus fetched counts correctly but does not say WHO is missing,
and who is missing is what has to be resolved and what has to be recorded if it
is not.
Audit dates. A separate pass with a separate predicate, date_created IS
NULL, over the whole table and not just over what this run fetched. Every
protein insert_proteins loaded carries NULL in all three columns – roughly
575.000 of some 680.000 rows at the time this was written – so a date filter
would have silently excluded 85% of the corpus while looking like it worked. Four
independent reviewers flagged that on 2026-10-05 before it shipped. The request is
fields-only, no sequence, so the responses are small, and the pass is a no-op
once it has run.
SECONDARY ACCESSIONS, THE ROUTE THAT LOOKS LIKE A DELETION.
/uniprotkb/accessions matches PRIMARY accessions only. An accession merged into
another entry – a secondary – is not returned, and UniProt counts it in
X-Total-Results regardless, so the response reports “7 results” with an empty
body and a 200. Measured 2026-10-05 over seven accessions, in FASTA (0 bytes) and
in JSON ({"results":[]}). The single-entry route DOES follow the merge and
redirects, so the same accession looks alive one way and deleted the other:
P30456 -> secondary of P04439 (HLA-A, which carries 135 secondaries) Q9NPA5 -> secondary of Q9NTW7 E1BZ05 -> secondary of P02542
HOW MUCH. On GOA 156, of 10,791 reliable accessions the batch endpoint did not
return, a systematic sample of 600 resolved 18.2% as merges; the rest are
DELETED with no successor. Of the recoverable ones, 72% already had their primary
in protein and 28% did not. Extrapolated: ~1,960 recoverable, ~558 proteins
genuinely absent and ~1,403 annotations the foreign key would have dropped even
though the protein was present under its primary accession.
WHAT THIS FIXES BEYOND COVERAGE. If GOA used P30456 in 2016 and P04439 today, a series over accessions sees one disappearance and one appearance where there is a single protein. That contaminates the very delta the campaign measures, and no amount of counting fixes it – only recording the link does.
HOW IT IS STORED, AND WHY IT DOES NOT DUPLICATE EMBEDDINGS. Two rows exist: the
primary as usual, and the secondary with canonical_accession pointing at it,
is_canonical=False and isoform_index=None. Both share a sequence_id,
because protea.core.operations._protein_store.store_records() deduplicates
sequences by hash – and embeddings are keyed on Sequence rather than
Protein (compute_embeddings.py), so two accessions over one sequence yield
ONE embedding and ONE neighbour in the KNN bank.
is_canonical is the population filter in every code path that counts proteins
(proteins_stats, proteins, showcase), and a merged secondary is not a
distinct protein to count, so the value is the correct one. What distinguishes it
from an isoform is isoform_index: an integer for an isoform, None for a
merge alias.
WHAT CANNOT BE RESCUED, AND WHY IT IS A LIST AND NOT A NUMBER. An accession
deleted from UniProt has no sequence to fetch, so it can never be embedded. Those
are written out as sin_resolver.txt in the artifact store, not just counted:
a number cannot be audited, a list can. Their annotations stay in the corpus –
the protein took part in the deltas – and every query that needs a chain filters
on sequence_id IS NOT NULL.
- class protea.core.operations.resolve_protein_sequences.ResolveProteinSequencesOperation#
Bases:
OperationFetch from UniProt everything the GAF could not say.
Runs ONCE, after the last
extract_goa_universepass of the series and before the embeddings. Safe to re-run: its population is “whatever still has no sequence”, so a second run asks only about what a first run could not resolve – which is bounded by the number of deleted accessions, some tens of thousands, a few seconds of requests.Runs on
protea.jobs.- description: str = 'Fetch sequences, audit dates and merged-accession links from UniProt for every protein row that lacks them. Runs once, after the GAF series has been extracted, because the sequences are needed over the union of the releases and not per release. Accessions UniProt no longer serves are written out as a list of names rather than reported as a count.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name: str = 'resolve_protein_sequences'#
- payload_model#
alias of
ResolveProteinSequencesPayload
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.resolve_protein_sequences.ResolveProteinSequencesPayload(*, timeout_seconds: Annotated[int, Gt(gt=0)] = 120, dry_run: bool = False, max_accessions: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0)])] | None = None)#
Bases:
ProteaPayload- dry_run: bool#
- max_accessions: Annotated[int, Field(gt=0)] | None#
Stop after this many candidates, for a smoke run before the real one. The value is REPORTED in the result as
limit, so a capped run can never be read as a complete one – which is the whole hazard of a bound like this.
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- timeout_seconds: Annotated[int, Field(gt=0)]#
- protea.core.operations.resolve_protein_sequences.resolution_key_for(job_id: Any, name: str) str#
Storage key for one artifact of this operation.
- load_goa_annotations
Bulk-loads a GAF (Gene Association Format) file. Annotations are filtered against canonical accessions present in the database, avoiding orphaned foreign keys. Each batch is committed independently to bound transaction size.
- class protea.core.operations.load_goa_annotations.LoadGOAAnnotationsOperation#
Bases:
objectStreams a GOA GAF file (gzip or plain) and upserts ProteinGOAnnotation rows.
The GAF file is streamed line by line from
gaf_url; it is never fully loaded into memory, making it suitable for the full UniProt GAF (hundreds of millions of lines).Only accessions present in the
proteintable are stored; all others are silently skipped. The canonical accession set is loaded once from the DB at the start of the operation.- GAF 2.2 columns used (1-indexed, tab-separated):
2 → DB_Object_ID (accession) 5 → GO ID 4 → Qualifier 7 → Evidence Code 6 → DB:Reference 8 → With/From 15 → Assigned By 14 → Date (YYYYMMDD)
- description = 'Stream a UniProt GOA GAF release line by line and bulk-insert ProteinGOAnnotation rows for accessions already present in the DB.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'load_goa_annotations'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.load_goa_annotations.LoadGOAAnnotationsPayload(*, ontology_snapshot_id: str, gaf_url: str, source_version: str, page_size: Annotated[int, Gt(gt=0)] = 10000, timeout_seconds: Annotated[int, Gt(gt=0)] = 300, commit_every_page: bool = True, total_limit: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0)])] | None = None, allow_unverified_ontology: bool = False)#
Bases:
ProteaPayload- allow_unverified_ontology: bool#
- commit_every_page: bool#
- gaf_url: str#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- ontology_snapshot_id: str#
- page_size: PositiveInt#
- source_version: str#
- timeout_seconds: PositiveInt#
- total_limit: PositiveInt | None#
- load_quickgo_annotations
Streams GO annotations from the QuickGO bulk download API (paginated TSV). Supports optional ECO→GO evidence code mapping and per-page commits. Filters out annotations whose accessions are not already in the database.
- class protea.core.operations.load_quickgo_annotations.LoadQuickGOAnnotationsOperation#
Bases:
objectStreams GO annotations from the QuickGO bulk download API.
Proteins to annotate are determined by the canonical accessions already present in the DB; no external FASTA or accession list is needed.
- The QuickGO TSV columns used:
GENE PRODUCT ID → protein accession GO TERM → GO identifier QUALIFIER → qualifier (enables, involved_in…) ECO ID → mapped to evidence_code via eco_mapping_url (or stored raw) REFERENCE → db_reference WITH/FROM → with_from ASSIGNED BY → assigned_by DATE → annotation_date
- description = "Stream GO annotations from QuickGO's bulk download endpoint and insert ProteinGOAnnotation rows for accessions already present in the DB."#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'load_quickgo_annotations'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.load_quickgo_annotations.LoadQuickGOAnnotationsPayload(*, ontology_snapshot_id: str, source_version: str, quickgo_base_url: str = 'https://www.ebi.ac.uk/QuickGO/services/annotation/downloadSearch', gene_product_ids: list[str] | None = None, use_db_accessions: bool = True, eco_mapping_url: str | None = None, page_size: Annotated[int, Gt(gt=0)] = 10000, timeout_seconds: Annotated[int, Gt(gt=0)] = 300, commit_every_page: bool = True, total_limit: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0)])] | None = None, gene_product_batch_size: Annotated[int, Gt(gt=0)] = 200)#
Bases:
ProteaPayloadPayload for loading GO annotations from the QuickGO bulk download endpoint.
QuickGO returns a single streamed TSV filtered by the canonical accessions already present in the DB; no external accession list is needed.
eco_mapping_url(optional) points to a GAF-ECO mapping file (space-separated:ECO:XXXXXXX CODE). When provided, ECO IDs are resolved to GO evidence codes (IDA, IEA…) before insertion. If omitted, the raw ECO ID is stored as-is inevidence_code.- commit_every_page: bool#
- eco_mapping_url: str | None#
- gene_product_batch_size: PositiveInt#
- gene_product_ids: list[str] | None#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- ontology_snapshot_id: str#
- page_size: PositiveInt#
- quickgo_base_url: str#
- source_version: str#
- timeout_seconds: PositiveInt#
- total_limit: PositiveInt | None#
- use_db_accessions: bool#
- compute_embeddings
Coordinator operation that partitions the target sequence set into batches and dispatches one
compute_embeddings_batchmessage per batch toprotea.embeddings.batch. The coordinator serialises on theprotea.embeddingsqueue (one at a time) to prevent concurrent model loads from exhausting GPU memory. Batch and write workers scale independently. Returnsdeferred=True; the parent job is closed by the last write worker.
- class protea.core.operations.compute_embeddings.ChunkEmbedding(chunk_index_s: int, chunk_index_e: int | None, vector: numpy.ndarray.(typing.Any, typing.Any))#
Bases:
objectOne pooled embedding for a contiguous residue span of a sequence.
chunk_index_sandchunk_index_euse the same convention as the PROTEA DB columns: start is 0-based inclusive, end is exclusive. When chunking is disabled,chunk_index_s=0andchunk_index_e=None(full sequence).- chunk_index_e: int | None#
- chunk_index_s: int#
- vector: numpy.ndarray.(typing.Any, typing.Any)#
- class protea.core.operations.compute_embeddings.StoreEmbeddingsOperation#
Bases:
objectWrites pre-computed embeddings to the DB and updates parent job progress.
Runs on a CPU-only worker (protea.embeddings.write queue) so the GPU worker is free to start the next inference batch immediately.
- description = "CPU child job: bulk-insert pre-computed pgvector embeddings and atomically increment the parent compute_embeddings job's progress."#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'store_embeddings'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.compute_embeddings.StoreEmbeddingsPayload(*, parent_job_id: str, skip_existing: bool = True, groups: list[StoredConfigEmbeddings])#
Bases:
ProteaPayloadPayload published by ComputeEmbeddingsBatchOperation after inference.
One message per batch carrying every config the pass served, so the write is all or nothing; see
build_store_message(). A message in the one-config shape is folded into a single group and behaves as it did.- groups: list[StoredConfigEmbeddings]#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- parent_job_id: str#
- skip_existing: bool#
- class protea.core.operations.compute_embeddings.StoredConfigEmbeddings(*, embedding_config_id: str, sequences: list[dict[str, Any]])#
Bases:
ProteaPayloadOne config’s share of a batch’s vectors inside a store message.
- embedding_config_id: str#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- sequences: list[dict[str, Any]]#
- predict_go_terms
Coordinator operation that loads reference embeddings into a process-level float16 cache, partitions the query set into batches, and dispatches one
predict_go_terms_batchmessage per batch toprotea.predictions.batch. Feature engineering (alignments, taxonomy) is opt-in via payload flags. Returnsdeferred=True; the parent job is closed by the last write worker.
Compatibility shim: re-exports every public + test-visible name from
the split submodules so existing imports of
protea.core.operations.predict_go_terms.* keep working.
T2B.6 (2026-05-16) split the monolithic 2096-LOC
protea/core/operations/predict_go_terms.py into this package:
_commonconstants + dataclasses + helper functions
_coordinatorPredictGOTermsOperation (KNN dispatcher)
_batch_opPredictGOTermsBatchOperation (CPU worker)
_batch_op_referencereference-pool loading mixin
_batch_op_featurefeature/annotation/embedding loading mixin
_batch_op_rerankerreranker scoring mixin
_aspect_helpersaspect-separated KNN pre-search + adapter prep
_storeStorePredictionsOperation (DB writer)
Everything imported below is re-exported so external callers keep using
the canonical protea.core.operations.predict_go_terms module path.
- class protea.core.operations.predict_go_terms.AdapterInputs(p: PredictGOTermsBatchPayload, valid_accessions: list[str], query_embeddings: np.ndarray, ref_data: dict[str, Any], annotations: dict[str, list[dict[str, Any]]], go_id_map: dict[int, str], go_aspect_map: dict[int, str], prediction_set_id: uuid.UUID, ref_sequences: dict[str, str], query_sequences: dict[str, str], ref_tax_ids: dict[str, int | None], query_tax_ids: dict[str, int | None], alignment_cache: Any = None, ref_sequence_identities: dict[str, str] | None = None)#
Bases:
NamedTupleBundle of data inputs the adapter consumes.
Keeps the public adapter functions under flake8-bugbear’s parameter ceiling.
ref_datacarries the unified reference pool the orchestrator already cached (embeddings_f32/embeddings_f32_cos/accessions); the adapter picks the cosine-normalised view when the payload’s metric is"cosine".- alignment_cache: Any#
Alias for field number 12
- annotations: dict[str, list[dict[str, Any]]]#
Alias for field number 4
- go_aspect_map: dict[int, str]#
Alias for field number 6
- go_id_map: dict[int, str]#
Alias for field number 5
- p: PredictGOTermsBatchPayload#
Alias for field number 0
- prediction_set_id: uuid.UUID#
Alias for field number 7
- query_embeddings: np.ndarray#
Alias for field number 2
- query_sequences: dict[str, str]#
Alias for field number 9
- query_tax_ids: dict[str, int | None]#
Alias for field number 11
- ref_data: dict[str, Any]#
Alias for field number 3
- ref_sequence_identities: dict[str, str] | None#
Alias for field number 13
- ref_sequences: dict[str, str]#
Alias for field number 8
- ref_tax_ids: dict[str, int | None]#
Alias for field number 10
- valid_accessions: list[str]#
Alias for field number 1
- class protea.core.operations.predict_go_terms.AdapterResult(predictions: list[dict[str, Any]], pair_features: dict[tuple[str, str], dict[str, Any]], neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]], go_map_by_aspect: dict[str, dict[str, list[dict[str, Any]]]], repaired_pair_features: int = 0)#
Bases:
NamedTupleOutput bundle: enriched predictions +
pair_featuresfor v6.pair_featuresis keyed by(q_acc, ref_acc)and carries the alignment / taxonomy columns the v6 enricher (KnnEnrichmentContext) expects.neighbors_by_aspectandgo_map_by_aspectare re-exported from the diagnostics so the v6 shim can reuse them without re-running KNN.- go_map_by_aspect: dict[str, dict[str, list[dict[str, Any]]]]#
Alias for field number 3
- neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]]#
Alias for field number 2
- pair_features: dict[tuple[str, str], dict[str, Any]]#
Alias for field number 1
- predictions: list[dict[str, Any]]#
Alias for field number 0
- repaired_pair_features: int#
How many
(query, donor)pairs the pre-search did not anticipate and this call had to compute after the fact. Expected to be 0. A non-zero value is not damage, the rows are repaired before they are returned, but it says the two searches disagreed and by how much.
- class protea.core.operations.predict_go_terms.AspectSeparatedKnnContext(valid_accessions: list[str], query_embeddings: numpy.ndarray, ref_data_by_aspect: dict[str, dict[str, Any]], annotation_set_id: UUID, prediction_set_id: UUID, payload: PredictGOTermsBatchPayload)#
Bases:
objectInputs for
PredictGOTermsBatchOperation._run_aspect_separated_knn.Same family as
BatchPredictContextbut for the aspect-separated KNN path: one independent index + neighbor set per GO aspect (P/F/C).ref_data_by_aspectis keyed by aspect char rather than the unifiedref_datadict that_predict_batchconsumes;annotation_set_idis required because aspect-scoped GO annotation lookups happen inside the helper.- annotation_set_id: UUID#
- payload: PredictGOTermsBatchPayload#
- prediction_set_id: UUID#
- query_embeddings: numpy.ndarray#
- ref_data_by_aspect: dict[str, dict[str, Any]]#
- valid_accessions: list[str]#
- class protea.core.operations.predict_go_terms.KnnEnrichmentContext(valid_accessions: list[str], query_embeddings: numpy.ndarray, neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]], go_map_by_aspect: dict[str, dict[str, list[dict[str, Any]]]], pair_features: dict[tuple[str, str], dict[str, Any]], pca_state: tuple[numpy.ndarray, numpy.ndarray] | None)#
Bases:
objectBundle of KNN-side inputs consumed by
enrich_v6_features().Groups the six per-call inputs that came out of the same KNN / aspect-pivot pipeline upstream (
predict_go_terms_batch) so the enrichment signature stays under flake8-bugbear’s parameter ceiling.- go_map_by_aspect: dict[str, dict[str, list[dict[str, Any]]]]#
- neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]]#
- pair_features: dict[tuple[str, str], dict[str, Any]]#
- pca_state: tuple[numpy.ndarray, numpy.ndarray] | None#
- query_embeddings: numpy.ndarray#
- valid_accessions: list[str]#
- class protea.core.operations.predict_go_terms.PredictGOTermsBatchOperation(reranker_scorer: RerankerScorer | None = None)#
Bases:
_ReferenceMixin,_FeatureLoadingMixinCPU batch worker: KNN search + GO annotation transfer for one query chunk.
Reference embeddings and their GO annotations are loaded from DB on first access and cached at the process level (_REF_CACHE). Subsequent batch messages reuse the cached reference without any DB round-trip.
Result is published to
protea.predictions.writefor bulk DB insertion. The reranker scoring path is delegated to an injectedRerankerScorercollaborator (T2B.4). The unified-pool, aspect-separated, post-KNN and chunked-publish helpers live in sibling modules (F2C.5c orchestrator collapse).- description = 'CPU child job: KNN search and GO annotation transfer for one query chunk; result is forwarded to store_predictions.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'predict_go_terms_batch'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.predict_go_terms.PredictGOTermsBatchPayload(*, embedding_config_id: str, annotation_set_id: str, ontology_snapshot_id: str, prediction_set_id: str, parent_job_id: str, query_accessions: list[str], query_set_id: str | None = None, limit_per_entry: Annotated[int, Gt(gt=0)] = 5, distance_threshold: float | None = None, exclude_self_neighbour: bool = False, search_backend: str = 'numpy', metric: str = 'cosine', faiss_index_type: str = 'Flat', faiss_nlist: int = 100, faiss_nprobe: int = 10, faiss_hnsw_m: int = 32, faiss_hnsw_ef_search: int = 64, compute_alignments: bool = True, compute_taxonomy: bool = True, compute_reranker_features: bool = True, compute_v6_features: bool = False, compute_classifier: bool = False, compute_self_prior: bool = False, compute_association: bool = False, compute_protst: bool = False, compute_lineage_features: bool = False, compute_ia: bool = False, ia_file: str | None = None, donor_policy: DonorPolicy = DonorPolicy(reviewed_only=False, evidence_codes=None, exclude_reference_prefixes=[]), expand_votes_to_ancestors: bool = False, aspect_separated_knn: bool = True, reranker_model_id: str | None = None, reranker_artifact_uri: str | None = None, reranker_feature_schema_sha: str | None = None, reranker_nk_artifact_uri: str | None = None, reranker_nk_feature_schema_sha: str | None = None, reranker_lk_artifact_uri: str | None = None, reranker_lk_feature_schema_sha: str | None = None, reranker_pk_artifact_uri: str | None = None, reranker_pk_feature_schema_sha: str | None = None)#
Bases:
ProteaPayloadPayload for one KNN batch dispatched by the coordinator.
- annotation_set_id: str#
- aspect_separated_knn: bool#
- compute_alignments: bool#
- compute_association: bool#
- compute_classifier: bool#
- compute_ia: bool#
- compute_lineage_features: bool#
- compute_protst: bool#
- compute_reranker_features: bool#
- compute_self_prior: bool#
- compute_taxonomy: bool#
- compute_v6_features: bool#
- distance_threshold: float | None#
- donor_policy: DonorPolicy#
- embedding_config_id: str#
- exclude_self_neighbour: bool#
- expand_votes_to_ancestors: bool#
- faiss_hnsw_ef_search: int#
- faiss_hnsw_m: int#
- faiss_index_type: str#
- faiss_nlist: int#
- faiss_nprobe: int#
- ia_file: str | None#
- limit_per_entry: PositiveInt#
- metric: str#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- ontology_snapshot_id: str#
- parent_job_id: str#
- prediction_set_id: str#
- query_accessions: list[str]#
- query_set_id: str | None#
- reranker_artifact_uri: str | None#
- reranker_feature_schema_sha: str | None#
- reranker_lk_artifact_uri: str | None#
- reranker_lk_feature_schema_sha: str | None#
- reranker_model_id: str | None#
- reranker_nk_artifact_uri: str | None#
- reranker_nk_feature_schema_sha: str | None#
- reranker_pk_artifact_uri: str | None#
- reranker_pk_feature_schema_sha: str | None#
- search_backend: str#
- class protea.core.operations.predict_go_terms.PredictGOTermsOperation#
Bases:
objectCoordinator: validates, creates PredictionSet, dispatches N batch messages.
Pipeline:
Validate
EmbeddingConfig,AnnotationSetandOntologySnapshot.Load query accessions that have embeddings (no embedding data; keeps the coordinator session light).
Create the
PredictionSet.Partition accessions into batches and publish to
protea.predictions.batch.
The actual KNN search and GO transfer happen inside
PredictGOTermsBatchOperation.- description = 'Coordinator: create a PredictionSet and partition query proteins into KNN batches dispatched to predict_go_terms_batch workers.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'predict_go_terms'#
- summarize_payload(payload: dict[str, Any], *, session: Session | None = None) str#
- class protea.core.operations.predict_go_terms.PredictGOTermsPayload(*, embedding_config_id: str, annotation_set_id: str, ontology_snapshot_id: str, query_accessions: list[str] | None = None, query_set_id: str | None = None, limit_per_entry: Annotated[int, Gt(gt=0)] = 5, distance_threshold: float | None = None, exclude_self_neighbour: bool = False, batch_size: Annotated[int, Gt(gt=0)] = 1024, search_backend: str = 'numpy', metric: str = 'cosine', faiss_index_type: str = 'Flat', faiss_nlist: int = 100, faiss_nprobe: int = 10, faiss_hnsw_m: int = 32, faiss_hnsw_ef_search: int = 64, compute_alignments: bool = True, compute_taxonomy: bool = True, compute_reranker_features: bool = True, compute_v6_features: bool = False, compute_lineage_features: bool = False, compute_classifier: bool = False, compute_self_prior: bool = False, compute_association: bool = False, compute_protst: bool = False, compute_ia: bool = False, ia_file: str | None = None, donor_policy: DonorPolicy = DonorPolicy(reviewed_only=False, evidence_codes=None, exclude_reference_prefixes=[]), expand_votes_to_ancestors: bool = False, aspect_separated_knn: bool = True, reranker_model_id: str | None = None, reranker_model_id_nk: str | None = None, reranker_model_id_lk: str | None = None, reranker_model_id_pk: str | None = None)#
Bases:
ProteaPayloadPayload for the
predict_go_termscoordinator job.- annotation_set_id: str#
- aspect_separated_knn: bool#
- batch_size: PositiveInt#
- compute_alignments: bool#
- compute_association: bool#
- compute_classifier: bool#
- compute_ia: bool#
- compute_lineage_features: bool#
- compute_protst: bool#
- compute_reranker_features: bool#
- compute_self_prior: bool#
- compute_taxonomy: bool#
- compute_v6_features: bool#
- distance_threshold: float | None#
- donor_policy: DonorPolicy#
- embedding_config_id: str#
- exclude_self_neighbour: bool#
Whether the query protein may be its own neighbour.
Default False, which is what every run before 2026-08-28 did, and the default is preserved so no stored result changes meaning. It is recorded either way, because a run that allows self-retrieval and a run that forbids it are two levels of the retriever and the record has to be able to tell them apart.
Measured on the campaign that prompted this: with self-retrieval allowed, the nearest neighbour is the query itself for 95.0 per cent of candidate rows at depth 1, and 81.8 per cent of the 14,032 query proteins have no other neighbour at that depth at all. A neighbourhood of one, where the one is yourself, is not a transfer.
When true the search asks for one more than it needs and drops the self hit, so
limit_per_entrykeeps meaning the number of real donors rather than the number of rows the index returned.
- expand_votes_to_ancestors: bool#
- faiss_hnsw_ef_search: int#
- faiss_hnsw_m: int#
- faiss_index_type: str#
- faiss_nlist: int#
- faiss_nprobe: int#
- ia_file: str | None#
- limit_per_entry: PositiveInt#
- metric: str#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- ontology_snapshot_id: str#
- query_accessions: list[str] | None#
- query_set_id: str | None#
- reranker_model_id: str | None#
- reranker_model_id_lk: str | None#
- reranker_model_id_nk: str | None#
- reranker_model_id_pk: str | None#
- search_backend: str#
- class protea.core.operations.predict_go_terms.StorePredictionsOperation#
Bases:
objectWrite worker: bulk-inserts GOPrediction rows and updates parent job progress.
Receives serialized prediction dicts from PredictGOTermsBatchOperation, inserts them into the DB, and atomically increments the parent Job’s progress counter. When the last batch is stored the parent Job is closed as SUCCEEDED.
- description = 'CPU child job: bulk-insert GOPrediction rows from a batch and atomically advance the parent predict_go_terms progress counter.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'store_predictions'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.predict_go_terms.StorePredictionsPayload(*, parent_job_id: str, prediction_set_id: str, predictions: list[dict[str, Any]], is_final_chunk: bool = True)#
Bases:
ProteaPayloadPayload carrying serialized prediction dicts to the write worker.
- is_final_chunk: bool#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- parent_job_id: str#
- prediction_set_id: str#
- predictions: list[dict[str, Any]]#
- protea.core.operations.predict_go_terms.apply_reranker(df: pandas.DataFrame, booster: lightgbm.Booster, *, feature_cols: list[str] | None = None) numpy.ndarray#
Score
dfwithboosterand return an aligned array.If
feature_colsis None we use the booster’s ownfeature_name(). Missing columns are filled withnp.nanso LightGBM routes them through its native missing-value branch rather than crashing on KeyError.
- protea.core.operations.predict_go_terms.call_pipeline_predict(inputs: AdapterInputs) AdapterResult#
Run
protea_method.pipeline.predictfor the unified-pool path.Returns the prediction dicts shaped exactly as PROTEA’s downstream consumers expect (
protea-method0.3.0 stamps every PROTEA field, includingprediction_set_idviaPredictConfig), plus the pair-feature dict the v6 enricher wants and the diagnostics’ aspect maps for the v6 context.
- protea.core.operations.predict_go_terms.call_pipeline_predict_aspect_separated(inputs: AdapterInputs, neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]]) AdapterResult#
Run
pipeline.predict(aspect_separated=True)for the per-aspect path.The caller has already KNN-searched each aspect’s pre-filtered reference pool and loaded the union of hit-ref annotations (across aspects).
protea-methodre-runs the partitioned KNN against the unified pool we pass. Both put a ref in aspecta’s bank iff at least one of its annotations resolves to aspecta, so the two searches see the same members.THEY DO NOT PRODUCE THE SAME NUMBERS. This docstring used to say the two were bit-exact; it is measurably not, and
_repair_pair_featuresbelow carries the measurement and repairs what the disagreement drops.The redundant KNN inside
pipeline.predict()keeps the delegation pure (no neighbour injection): the numpy arrays are warm in L3 by then, so the cost is dwarfed by the annotation and sequence loads the pre-search saved. Believing it was also exact is what made this class of defect invisible.
- protea.core.operations.predict_go_terms.enrich_v6_features(predictions: list[dict[str, Any]], *, session: Session, ctx: KnnEnrichmentContext, compute_taxonomy: bool) None#
Compute the 25 v6 features and merge them into each
preddict in place.PROTEA-side wrapper around
protea_method.feature_enricher.enrich_v6_features: collects the GO term ids in play, loads the metadata maps from the database, and forwards everything to the library function. The library does the Anc2Vec pool, neighbor centroids, tax voters, PCA projection, and per-row merge.
- protea.core.operations.predict_go_terms.infer_active_feature_families(*, compute_alignments: bool, compute_taxonomy: bool, compute_v6_features: bool, compute_lineage_features: bool = False) list[str]#
Map predict-time feature flags onto lab feature families.
Thin PROTEA-side extension of
protea_method.reranker.infer_active_feature_families(): it delegates to the library helper for the base families (knn/annotation_meta/alignment_nw/length/taxonomy_pair/ the v6 bundle) and layers the GO-DAGlineagefamily on top whencompute_lineage_featuresis set.The lineage family is governed here (not in the library) because it is opt-in at serve time via the
compute_lineage_featurespayload flag and must round-trip throughprotea_contracts.compute_feature_schema_sha()so a booster trained with lineage gets a matching live schema sha.Invariant (load-bearing for the FARM-EXP.5 schema-sha guard): with
compute_lineage_features=False(the default) the returned family list is byte-identical to the library output for every align/tax/v6 combination, so the eight existing schema shas (registered trio7fcecf26aa0aetc.) are unchanged. Setting the flag appends exactly thelineagefamily, yielding a new sha (e.g. align+tax+no-v6+lineage ->0810bef8fd4d).
- protea.core.operations.predict_go_terms.load_reranker(artifact_uri: str, *, feature_schema_sha: str, store: ArtifactStore, cache_dir: Path | None = None) lightgbm.Booster#
Fetch (once) and load a LightGBM booster by URI.
The first call materialises the booster blob under
cache_dir/<feature_schema_sha>_<uri_tag>.txt; subsequent calls reuse the on-disk file and an in-process booster cache keyed by the URI.storeis used only when the cached file does not exist;artifact_uriis expected to resolve to a store key but the store implementation chooses whether to parse it (LocalFsArtifactStoreignores the URI and resolves keys from its root; MinIO derives the key from thes3://bucket/keyURI).The on-disk cache is namespaced by
feature_schema_shabecause each sha represents a stable column layout; multiple boosters that share a sha need to disambiguate by URI to avoid the in-process cache returning the first-loaded booster for every cell.
- protea.core.operations.predict_go_terms.load_settings(project_root: Path, *, env_prefix: str = 'PROTEA_') Settings#
Resolve runtime settings via env >
.env>system.yaml> defaults.See the module docstring for the full env-var contract and the deprecation matrix.
env_prefixdefaults to"PROTEA_"; passing anything else emits aDeprecationWarning.
- protea.core.operations.predict_go_terms.search_knn(*args, **kwargs)#
Pass through to
protea_method.knn_search.search_knn.Syncs the PROTEA tuning knob into the env var on first call, and pins the device to CPU unless the caller asked for something else.
- generate_evaluation_set
Computes the NK/LK/PK evaluation delta between two annotation sets using the CAFA5 protocol (experimental evidence only, NOT-propagation through the GO DAG, per-namespace classification). Stores an
EvaluationSetrow with summary statistics. Ground-truth files are generated on-demand by the download endpoints.
- class protea.core.operations.generate_evaluation_set.GenerateEvaluationSetOperation#
Bases:
objectComputes the CAFA evaluation delta between two GOA annotation sets.
Applies experimental evidence code filtering, NOT-qualifier exclusion with GO DAG descendant propagation, and classifies delta proteins into NK/LK.
Stores an EvaluationSet row with summary statistics. The actual ground-truth rows are computed on-demand by the download endpoints using the same logic.
- description = 'Compute the CAFA delta between an old and a new GOA annotation set, split delta proteins into NK/LK and persist an EvaluationSet. Supports cross-OBO reconciliation via an optional pivot snapshot.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'generate_evaluation_set'#
- summarize_payload(payload: dict[str, Any], *, session: Session | None = None) str#
- class protea.core.operations.generate_evaluation_set.GenerateEvaluationSetPayload(*, old_annotation_set_id: str, new_annotation_set_id: str, pivot_ontology_snapshot_id: str | None = None, old_native_snapshot_id: str | None = None, new_native_snapshot_id: str | None = None, window_role: str | None = None, truth_profile: str = 'as_closed', toi_rule: str = 'pivot_terms', not_codes: str = 'any', holdout_waiver: str | None = None, prospective_declaration: str | None = None)#
Bases:
ProteaPayload- holdout_waiver: str | None#
The sentence a caller must repeat verbatim to build a window that reads past the board’s mark. Deliberately not a boolean: the holdout is meant to be scored once, at the end, and a flag that can be set by reflex is a flag that gets set by reflex. See split_registry.HOLDOUT_WAIVER.
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- new_annotation_set_id: str#
- new_native_snapshot_id: str | None#
- not_codes: str#
- old_annotation_set_id: str#
- old_native_snapshot_id: str | None#
- pivot_ontology_snapshot_id: str | None#
- prospective_declaration: str | None#
a band BEYOND the spent holdout, which begins at or after it and therefore cannot be a second look at it. Separate from the waiver because the waiver says of itself that it is the single pass, and that pass is written on a row already. Honoured only when the window’s start is at or after the band’s end; a straddle is refused by name. See split_registry.PROSPECTIVE_DECLARATION.
- Type:
The other sentence
- classmethod snapshot_opt_non_empty(v)#
- toi_rule: str#
- truth_profile: str#
- window_role: str | None#
- classmethod window_role_in_vocab(v)#
- run_cafa_evaluation
Runs
cafaevalfor NK, LK, and PK settings against a given prediction set. Downloads the OBO file, writes ground-truth and prediction TSVs, callscafa_eval()three times (NK and LK without-known, PK withpk_known_terms.tsvas-known), and persists anEvaluationResultrow with per-namespace Fmax, precision, recall, τ, and coverage.
- class protea.core.operations.run_cafa_evaluation.RunCafaEvaluationOperation#
Bases:
objectRuns the CAFA evaluator against NK, LK and PK settings.
Steps:
Load
EvaluationSetandPredictionSetfrom DB.Compute evaluation data (delta NK/LK + known terms) with full NOT propagation.
Download the OBO file from the ontology snapshot URL.
Resolve the Information Accretion (IA) file: if
ia_fileis set in the payload, use that path directly; otherwise, if theOntologySnapshothas ania_url, download it to a temporary file; if neither is set, cafaeval runs with uniform IC=1. IA weights make rare GO terms count more than common ones and are recommended for publishable evaluations.Write temp files: ground-truth NK/LK, known-terms, predictions (CAFA format).
Call
cafa_evalfor each setting (NK, LK, PK).Parse per-namespace Fmax / precision / recall / coverage from results.
Persist an
EvaluationResultrow with all metrics.
- description = 'Run the CAFA evaluator (NK/LK/PK) against an EvaluationSet using a PredictionSet, optionally weighted by Information Accretion.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'run_cafa_evaluation'#
- summarize_payload(payload: dict[str, Any], *, session: Session | None = None) str#
- load_interpro_go_mapping
Downloads and persists the InterPro-to-GO mapping file, linking InterPro domain entries to their associated GO terms. Used as a prerequisite step before running InterProScan-based annotation.
IP.4a — InterPro2GO mapping loader.
Streams the EBI interpro2go flat file (one line per InterPro entry
to GO term mapping) and upserts rows into interpro_go_mapping.
The file is small enough (few thousand lines, ~1 MB) to hold in
memory, but the operation still parses lazily so a partial read is
graceful.
Idempotent: the unique key
(ipr_accession, go_id, source_version) is enforced by an
ON CONFLICT DO NOTHING upsert, so re-running the operation for
the same release is a no-op.
InterPro2GO line format (text, comment-prefixed with !):
InterPro:IPR000001 Kringle > GO:protein binding ; GO:0005515
The pattern is:
InterPro:<IPR_ACCESSION> <human_label> > GO:<label> ; <GO_ID>
Evidence is implicit (curator-asserted IEA in the consuming pipeline)
so the evidence column captures the literal upstream label
("IEA" by default) without inventing extra metadata.
- class protea.core.operations.load_interpro_go_mapping.LoadInterProGoMappingOperation#
Bases:
objectStream the EBI InterPro2GO file and upsert mapping rows.
- description = 'Download the EBI InterPro2GO flat file and upsert (ipr_accession, go_id) rows into interpro_go_mapping; idempotent per source_version.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'load_interpro_go_mapping'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.load_interpro_go_mapping.LoadInterProGoMappingPayload(*, source_version: str, mapping_url: str = 'https://ftp.ebi.ac.uk/pub/databases/GO/goa/external2go/interpro2go', evidence: str = 'IEA', timeout_seconds: Annotated[int, Gt(gt=0)] = 120, chunk_size: Annotated[int, Gt(gt=0)] = 1000)#
Bases:
ProteaPayloadPayload for
load_interpro_go_mapping.mapping_urldefaults to the canonical EBI endpoint so callers can dispatch the op without a payload body in the common case.source_versionis required so the snapshot is queryable later; pass the InterPro release tag (e.g."InterPro-104.0") here.- chunk_size: PositiveInt#
- evidence: str#
- mapping_url: str#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- source_version: str#
- timeout_seconds: PositiveInt#
- run_interproscan_batch
Submits sequences to the EBI InterProScan REST API in configurable batch sizes. Stores
InterproAnnotationrows linking each protein to its domain signatures. Supports resume via previously stored job IDs.
run_interproscan_batch operation.
Runs InterProScan against a batch of proteins in fixed-size chunks,
parses the resulting TSV through the InterProSource plugin
(IP.1b), and bulk-inserts InterProAnnotation rows (IP.2).
Inputs are either a query_set_id (resolved via
QuerySetEntry joins) or an explicit accessions list. An
optional ipr_release_floor lets re-runs at a newer release skip
proteins whose latest persisted annotation already meets the floor.
Per-chunk commits + emit progress events make the run resumable:
re-dispatching the same payload picks up where the prior run left off
because already-annotated proteins are filtered out via the same
ipr_release_floor check on every invocation.
Out of scope for IP.3 (see slice spec):
The payload class lives in PROTEA for now; promotion to
protea-contractsis a follow-up bookkeeping commit.InterProScan installation runbook (post-defensa).
- class protea.core.operations.run_interproscan_batch.RunInterProScanBatchOperation#
Bases:
objectAnnotate a batch of proteins with InterProScan and persist hits.
Workflow:
Resolve target accessions (query set or explicit list).
Drop already-annotated ones if a
ipr_release_flooris set.Fetch sequences in one DB roundtrip.
For each
chunk_sizechunk: write a temp FASTA, invokeInterProSource.run, bulk-insert the parsed records, commit (optionally), and emit a progress event.
- description = 'Run InterProScan on a batch of proteins in fixed-size chunks and persist parsed domain hits into the interpro_annotation table.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'run_interproscan_batch'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.run_interproscan_batch.RunInterProScanBatchPayload(*, query_set_id: str | None = None, accessions: list[str] | None = None, ipr_release_floor: str | None = None, chunk_size: Annotated[int, ~annotated_types.Gt(gt=0)] = 50, timeout_seconds: Annotated[int, ~annotated_types.Gt(gt=0)] = 3600, extra_args: list[str] = <factory>, binary_path: str | None = None, commit_every_chunk: bool = True)#
Bases:
ProteaPayloadInputs for one
run_interproscan_batchinvocation.Exactly one of
query_set_id/accessionsmust be provided.ipr_release_flooris optional: when set, proteins whose latest persistedInterProAnnotation.ipr_releaseis lexicographically greater than or equal to the floor are skipped, which gives the re-dispatch flow its resume semantics.- accessions: list[str] | None#
- binary_path: str | None#
- chunk_size: PositiveInt#
- commit_every_chunk: bool#
- exactly_one_input() RunInterProScanBatchPayload#
- extra_args: list[str]#
- ipr_release_floor: str | None#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str | None) str | None#
- classmethod must_be_non_empty_list(v: list[str] | None) list[str] | None#
- query_set_id: str | None#
- timeout_seconds: PositiveInt#
- predict_go_terms_from_interpro
Derives GO term predictions from stored
InterproAnnotationrows and theInterproGoMappingtable, without running KNN search. Produces aPredictionSetwhose entries are directly evidence-backed by domain-matching rather than embedding distance.
IP.4b-PRED — InterPro-only GO term predictor.
A parallel-signal GO term predictor. Given a set of query proteins
whose InterProScan hits are already persisted as
InterProAnnotation rows (IP.2 / IP.3), this operation:
Joins each protein’s distinct InterPro accessions against the
InterProGoMappingtable (IP.4a — InterPro2GO loader) at the requestedsource_version.Resolves the right-hand GO ids against an
OntologySnapshotso the output is keyed bygo_term_idlike every otherGOPrediction.Aggregates the per-protein votes: if N distinct InterPro entries on the same protein map to the same GO term, that’s N supporting votes and a stronger prediction than a single mapping.
Persists the result as a fresh
PredictionSetwithmeta["algorithm"] = "interpro_propagation"so downstream ensemble / cafaeval routers can pick it up alongside KNN-basedPredictionSetrows (T-RES.3 ensemble multi-K scaffolding).
The operation is single-stage (no batch fan-out): the join is a cheap index scan and the per-protein InterPro hit count is tiny (O(10-100)) so partitioning would be pure overhead.
Idempotency#
Within one call: per-protein duplicate (go_term_id) votes are
merged before insert. Across calls: every call materialises a new
PredictionSet; the predictions underneath it are unique
by uq_go_prediction_set_protein_term and we additionally
ON CONFLICT DO NOTHING so a partial-failure retry on the same
prediction set inserts no duplicates.
GOPrediction column mapping#
The GOPrediction schema was designed for KNN transfer, so a
few NOT-NULL columns need a sensible value for the InterPro path:
ref_protein_accession— the InterPro accession that voted for this term, e.g."IPR000001". Multiple voters: the one with the lexicographically smallest accession (stable, observable).distance— the inverse vote count (1.0 / vote_count). Lower = stronger support, matching the KNN convention; a 1-voter prediction has distance 1.0, a 5-voter prediction 0.2.evidence_code— propagated from theInterProGoMapping.evidencecolumn (defaults to"IEA").vote_count— the literal number of distinct IPR entries on this protein that map to this GO id at thissource_version.
Out of scope (see IP.4 plan-first sub-plan):
Reranker feature integration (IP.4c,
requires_human=true).Score blending across PredictionSets (T-RES.3 ensemble router).
Ancestor / aspect propagation (the caller is expected to enable the existing post-process pipeline if needed).
- class protea.core.operations.predict_go_terms_from_interpro.PredictGOTermsFromInterProOperation#
Bases:
objectEmit GO predictions for proteins via their persisted InterPro hits.
Single-stage operation: validates FKs, materialises one
PredictionSet, performs an indexed three-table join (interpro_annotation⨝interpro_go_mapping⨝go_term), aggregates per-protein votes, and bulk-inserts theGOPredictionrows.- description = "Predict GO terms for a query set by joining each protein's InterProAnnotation rows against the InterPro2GO mapping table; emits a PredictionSet tagged algorithm=interpro_propagation."#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'predict_go_terms_from_interpro'#
- summarize_payload(payload: dict[str, Any]) str#
- class protea.core.operations.predict_go_terms_from_interpro.PredictGOTermsFromInterProPayload(*, embedding_config_id: str, annotation_set_id: str, ontology_snapshot_id: str, source_version: str, query_set_id: str | None = None, query_accessions: list[str] | None = None, ipr_release_floor: str | None = None, chunk_size: int = 1000)#
Bases:
ProteaPayloadInputs for
predict_go_terms_from_interpro.Either
query_set_idorquery_accessionsis required. Both may be set — the union is used.embedding_config_id,annotation_set_id,ontology_snapshot_idare required by the existingPredictionSetschema (NOT NULL FKs); for this parallel signal they act as trace pointers (the model wasn’t actually used during prediction).source_versionis the InterPro2GO mapping release tag (seeLoadInterProGoMappingPayload). Predictions are filtered to mappings tagged with this exactsource_versionso a release skew between snapshots is observable rather than silently mixed.- annotation_set_id: str#
- chunk_size: int#
- embedding_config_id: str#
- ipr_release_floor: str | None#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- ontology_snapshot_id: str#
- query_accessions: list[str] | None#
- query_set_id: str | None#
- source_version: str#
- export_research_dataset
Publishes the frozen re-ranker dataset (
train.parquet/eval.parquet/manifest.json) consumed byprotea-reranker-lab. Runs the KNN + feature-generation pipeline viaTrainRerankerAutoOperationindump_onlymode and uploads the resulting artefacts through the configuredArtifactStore(local FS by default, MinIO when thestoragecompose profile is active). Manifest records PROTEA’sproducer_version/producer_git_shafor full traceability from lab runs back to PROTEA HEAD.
Export a frozen re-ranker dataset for protea-reranker-lab.
Runs the same KNN + feature-generation pipeline as the now-renamed
research dataset dump helper (training_dump_helpers), skips the
LightGBM training stage, and publishes the resulting parquets +
manifest via the configured
ArtifactStore (local FS by
default, MinIO when enabled via the storage compose profile).
Why a dedicated operation instead of dump-only mode of the helper?
Narrower payload: only the knobs that matter for export, no LightGBM-specific fields.
Routes output through the storage abstraction, so the lab can consume from MinIO without every export having to know a local dump path on the API host.
Records
producer_version/producer_git_shain the manifest so any lab run can be traced back to a PROTEA HEAD.
- class protea.core.operations.export_research_dataset.ExportResearchDatasetOperation#
Bases:
object- description = 'Generate a frozen reranker dataset (train/eval parquets + manifest) and publish it to the configured artifact store.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
Run the export in three short session windows.
The compute phase (KNN search + parquet staging + upload) can take 3-4 hours. Holding a single SQLAlchemy session open across that span ends in tears: pool recycle / idle timeouts / pika reconnects all conspire to detach the session by the time we try to insert the Dataset row, which then raises
DetachedInstanceErrorand loses the work.Layout:
Window 1 (uniqueness check) uses the session handed in by BaseWorker. We touch it just long enough to verify the name is free, then release it.
Window 2 (compute) opens its own short-lived session for the dump helper, since its SQL is structured as many small reads rather than one long transaction.
Window 3 (register) opens a fresh
session_scopeto insert the Dataset row. That session is born after the long compute phase, so its connection is guaranteed healthy.
The BaseWorker-supplied session is left untouched after window 1 so the success/failure commit at the end of the worker loop runs against a fresh-enough connection (
_rebind_jobin BaseWorker handles the residual detachment risk for the Job ORM itself).
- name = 'export_research_dataset'#
- summarize_payload(payload: dict[str, Any], *, session: Session | None = None) str#
- class protea.core.operations.export_research_dataset.ExportResearchDatasetPayload(*, embedding_config_id: str, ontology_snapshot_id: str, train_versions: list[int], test_versions: list[int], annotation_source: str = 'goa', output_name: str, k: Annotated[int, Gt(gt=0)] = 5, search_backend: str = 'faiss', compute_alignments: bool = False, compute_taxonomy: bool = False, compute_anc2vec: bool = False, expand_votes_to_ancestors: bool = False, use_embedding_pca: bool = False, compute_self_prior: bool = False, compute_association: bool = False, compute_classifier: bool = False, compute_protst: bool = False, stable_feature_cache: bool = False, classifier_variants: list[dict[str, str]] | None = None)#
Bases:
ProteaPayloadPayload for the
export_research_datasetoperation.- annotation_source: str#
- classmethod at_least_one_test(v: list[int]) list[int]#
- classmethod at_least_two_train(v: list[int]) list[int]#
- classifier_variants: list[dict[str, str]] | None#
- compute_alignments: bool#
- compute_anc2vec: bool#
See TrainRerankerAutoPayload.compute_anc2vec. Exposed here so a ladder export can say it is not asking for those two families, rather than discovering at phase five that it cannot have them.
- compute_association: bool#
- compute_classifier: bool#
- compute_protst: bool#
- compute_self_prior: bool#
- compute_taxonomy: bool#
- embedding_config_id: str#
- expand_votes_to_ancestors: bool#
- k: PositiveInt#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- ontology_snapshot_id: str#
- output_name: str#
- search_backend: str#
- stable_feature_cache: bool#
- test_versions: list[int]#
- train_versions: list[int]#
- use_embedding_pca: bool#
Training-dump helpers#
protea.core.training_dump_helpers is the home of the KNN /
feature-generation helpers that were extracted in F0 (T0.6) when
protea.core.operations.train_reranker was deleted. The module is
deliberately not an operation: it is reused in-process by
ExportResearchDatasetOperation to materialise train and
eval shards before the parquet_export consolidation pass.
LightGBM training itself lives in
protea-reranker-lab,
which consumes the published Dataset rows produced by
export_research_dataset.
As of T-RES.1 (PR #368), parent_map_str is always passed to the KNN
transfer runner unconditionally, regardless of the expand_votes_to_ancestors
flag. The lineage producer (protea_method.lineage.compute_lineage_features)
requires the parent map for its lineage_* column computation; the flag only
controls ancestor-vote expansion, not the availability of the map itself.
Helpers used to generate frozen re-ranker datasets in-process.
Survives as a container for the KNN, feature-engineering,
streaming-parquet, and reference-loading utilities consumed by
ExportResearchDatasetOperation. The module used to expose two
operations (single-pair and multi-split training) wired into the
OperationRegistry; LightGBM training itself moved to the standalone
protea-reranker-lab repo, so the operations are unregistered.
TrainRerankerAutoOperation.execute() still runs the dump pipeline
(KNN + feature generation + parquet emission) for the export operation
in dump_only=True mode.
All execution is in-process; no RabbitMQ coordination.
T2B.6 (2026-05-16): the body of this module was extracted into the
protea.core.training_dump package so each submodule stays under the
§3 file-LOC ceiling. This file is preserved as a re-export shim so
existing imports of protea.core.training_dump_helpers.* keep
working. New code should import from the canonical submodules:
protea.core.training_dump._contextsparameter objects
protea.core.training_dump._payloadTrainRerankerAutoPayload
protea.core.training_dump._data_loadersbulk loaders
protea.core.training_dump._knn_transfer_knn_transfer_and_label
protea.core.training_dump._test_splittest split orchestration
protea.core.training_dump._train_splitper-pair train loop
protea.core.training_dump._runner_DumpRunner + auto op
- class protea.core.training_dump_helpers.KnnTransferContext(valid_queries: list[str], query_emb: np.ndarray, ref_by_aspect: dict[str, dict[str, Any]], go_id_map: dict[int, str], aspect_map: dict[int, str], gt_pairs: set[tuple[str, str]], query_known_gos: dict[str, set[str]] | None = None, parent_map_str: dict[str, set[str]] | None = None, ia_weights: dict[str, float] | None = None, pca_state: tuple[np.ndarray, np.ndarray] | None = None, pivot_go_ids: set[str] | frozenset[str] | None = None, embedding_pool: np.ndarray | None = None, t0_annotation_set_id: uuid.UUID | None = None)#
Bases:
objectBundle of KNN inputs + enrichment maps for
_knn_transfer_and_label.Groups the 12 per-call data arguments (queries, references, ontology maps, optional enrichment helpers) so the entry-point signature stays under flake8-bugbear’s parameter ceiling.
session, payloadp,sequence_context, andstream_outputremain standalone arguments because they are configuration / IO concerns, not data.- aspect_map: dict[int, str]#
- embedding_pool: np.ndarray | None = None#
- go_id_map: dict[int, str]#
- gt_pairs: set[tuple[str, str]]#
- ia_weights: dict[str, float] | None = None#
- parent_map_str: dict[str, set[str]] | None = None#
- pca_state: tuple[np.ndarray, np.ndarray] | None = None#
- pivot_go_ids: set[str] | frozenset[str] | None = None#
- query_emb: np.ndarray#
- query_known_gos: dict[str, set[str]] | None = None#
- ref_by_aspect: dict[str, dict[str, Any]]#
- t0_annotation_set_id: uuid.UUID | None = None#
- valid_queries: list[str]#
- class protea.core.training_dump_helpers.SequenceContext(query_sequences: dict[str, str] | None = None, ref_sequences: dict[str, str] | None = None, query_tax_ids: dict[str, int | None] | None = None, ref_tax_ids: dict[str, int | None] | None = None)#
Bases:
objectPer-protein sequence and taxonomy lookups.
All four attributes are optional; passing
Nonedisables the corresponding feature family (alignment / taxonomy).- query_sequences: dict[str, str] | None = None#
- query_tax_ids: dict[str, int | None] | None = None#
- ref_sequences: dict[str, str] | None = None#
- ref_tax_ids: dict[str, int | None] | None = None#
- class protea.core.training_dump_helpers.StreamOutput(output_parquet: Path, chunk_rows: int = 100000)#
Bases:
objectStreaming parquet output for memory-bounded dataset generation.
When provided,
_knn_transfer_and_labelwrites labeled rows directly tooutput_parquetin chunks ofchunk_rowsinstead of accumulating the full result list in memory.- chunk_rows: int = 100000#
- output_parquet: Path#
- class protea.core.training_dump_helpers.TrainRerankerAutoOperation#
Bases:
objectAutomated multi-split temporal holdout re-ranker training.
Trains 3 per-category models (NK, LK, PK) in a single execution. Each model trains on all aspects combined, giving it ~3x more data than per-aspect models and better convergence.
Pipeline:
Resolve annotation set IDs from version numbers.
Load GO maps once; optionally load IA weights for sample weighting.
For each consecutive pair in
train_versions, compute the evaluation delta (all 3 categories at once), load references and query embeddings, run KNN + GO transfer, and label predictions against each category’s ground truth.For each category (NK, LK, PK), concatenate the labeled data from all splits, train one LightGBM model with optional IA sample weights, evaluate on the test split, and store a
RerankerModelas{name}-{category}.
- description = 'Run KNN + feature generation across multiple temporal holdout pairs and emit frozen parquets. Originally also trained LightGBM models; that path now lives in protea-reranker-lab.'#
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
- name = 'research_dataset_dump_helper'#
- summarize_payload(payload: dict[str, Any], *, session: Session | None = None) str#
- class protea.core.training_dump_helpers.TrainRerankerAutoPayload(*, name: str, embedding_config_id: str, ontology_snapshot_id: str, train_versions: list[int], test_versions: list[int], evaluation_set_ids: list[str] = [], annotation_source: str = 'goa', limit_per_entry: Annotated[int, Gt(gt=0)] = 5, distance_threshold: float | None = None, search_backend: str = 'faiss', metric: str = 'cosine', faiss_index_type: str = 'IVFFlat', faiss_nlist: int = 256, faiss_nprobe: int = 32, num_boost_round: int = 1000, early_stopping_rounds: int = 50, val_fraction: float = 0.2, neg_pos_ratio: float | None = None, reranker_objective: str = 'binary', compute_alignments: bool = False, compute_taxonomy: bool = False, compute_anc2vec: bool = False, compute_self_prior: bool = False, compute_association: bool = False, compute_classifier: bool = False, compute_protst: bool = False, parity_chunk_size: int = 512, ia_file: str | None = None, expand_votes_to_ancestors: bool = False, use_embedding_pca: bool = False, training_scope: str = 'per_category', per_cell_min_positives: Annotated[int, Gt(gt=0)] = 200, dump_to: str | None = None, dump_only: bool = False, stable_feature_cache: bool = False, classifier_variants: list[dict[str, str]] | None = None)#
Bases:
ProteaPayloadPayload for the dump_helper operation.
Generates consecutive temporal pairs from
train_versions, runs KNN once per pair, then trains 3 per-category LightGBM models (NK, LK, PK) and evaluates each on the held-out test split.- annotation_source: str#
- classmethod at_least_one_test(v: list[int]) list[int]#
- classmethod at_least_two_train(v: list[int]) list[int]#
- classifier_variants: list[dict[str, str]] | None#
- compute_alignments: bool#
- compute_anc2vec: bool#
Compute the two anc2vec families. False by default, and that default is a record rather than a choice: the index they need is produced by no registered operation, so on a host without the npz the phases raised FileNotFoundError at phase five, after the KNN and three feature passes had run. With the index absent the columns were never produced anyway. Asking for them without the artefact still raises – the flag gates the attempt, it does not invent the data.
- compute_association: bool#
- compute_classifier: bool#
- compute_protst: bool#
- compute_self_prior: bool#
- compute_taxonomy: bool#
- distance_threshold: float | None#
- dump_only: bool#
- dump_to: str | None#
- early_stopping_rounds: int#
- embedding_config_id: str#
- evaluation_set_ids: list[str]#
WHICH declared window each pair’s truth comes from, by id. A SET of ids and not a list parallel to the pairs, because the pairs are generated from
train_versionsand a position nobody can check is a position that silently shifts.Empty is the old behaviour and still works wherever a pair has exactly one window. It does not work on this campaign: the three propagation graphs and the three truth rules are part of a window’s identity, so 62 of 69 distinct pairs already carry more than one, and the export refuses rather than guess. Naming is how a dump says which truth it trained on, which is the part that moves and the part a dataset could not previously record.
Every named window’s
pivot_snapshot_idhas to equalontology_snapshot_id: a window on another pivot expresses its truth on another term axis, and a manifest declaring one axis over windows using another is wrong about its own vocabulary.
- expand_votes_to_ancestors: bool#
- faiss_index_type: str#
- faiss_nlist: int#
- faiss_nprobe: int#
- ia_file: str | None#
- limit_per_entry: PositiveInt#
- metric: str#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- name: str#
- neg_pos_ratio: float | None#
- num_boost_round: int#
- ontology_snapshot_id: str#
- parity_chunk_size: int#
- per_cell_min_positives: PositiveInt#
- reranker_objective: str#
- classmethod scope_is_valid(v: str) str#
- search_backend: str#
- stable_feature_cache: bool#
- test_versions: list[int]#
- train_versions: list[int]#
- training_scope: str#
- use_embedding_pca: bool#
- val_fraction: float#
- protea.core.training_dump_helpers.load_evaluation_data_for_set(session: Session, eval_set) tuple[EvaluationData, UUID]#
Load ground-truth for an EvaluationSet row.
Strict reuse path: if
eval_set.groundtruth_uriis set, deserializes the persisted parquet via the configured ArtifactStore and returns it. If not set, raises — recomputation on-the-fly is intentionally not allowed (see the project’s “no on-the-fly reuse” rule). Usescripts/backfill_evaluation_groundtruth.pyto materialize artifacts for legacy EvaluationSet rows that predate this column.Returns the EvaluationData plus the pivot OntologySnapshot ID — the caller should use the pivot snapshot (not the old set’s) when loading the OBO for cafaeval, since propagated go_ids live in pivot term space.
Internal helpers#
These modules are imported by the operations and the feature engineering layer; they are documented here for completeness but are not part of the public API.
protea.core.anc2vec_embeddings: anc2vec ancestry embeddings for GO terms, used as features by the re-ranker.protea.core.annotation_intern: string interning helper for reducing memory pressure when loading large annotation sets.protea.core.disk_cache: generic on-disk cache with TTL used by the KNN reference loader and the PCA cache.protea.core.feature_enricher: orchestrator that combines alignment, taxonomy and anc2vec features into a single per-candidate row.protea.core.pca_cache: per-PLM PCA projection cache, used to pre-compute theemb_pcafeature family.protea.core._anc2vec_phases: phase helpers for the anc2vec embedding pipeline.protea.core._feature_enricher_helpers: low-level helpers extracted fromfeature_enricherto keep per-phase logic self-contained.protea.core.features._bindings: internal feature-column binding declarations consumed byfeatures.registry.protea.core._knn_transfer_runner: worker-side KNN transfer runner dispatched by the predictions coordinator.protea.core._leaf_record_builder: builder for leaf-prediction records in the KNN transfer pipeline.protea.core._pair_feature_compute: pair-level feature computation with optional process-pool parallelism and SQLite alignment cache.protea.core._training_dump_loaders: data-loading helpers used by the training-dump pipeline.protea.core.training_dump._constants: shared constants for the training-dump subpackage.protea.core.training_dump._contexts: context dataclasses bundling session, settings, and configuration for training-dump passes.protea.core.training_dump._data_loaders: loaders that hydrate protein, embedding, and annotation data for the training-dump pipeline.protea.core.training_dump._knn_transfer: KNN search and GO-term transfer logic specific to the training-dump path.protea.core.training_dump._payload: Pydantic payload model for theexport_research_datasetoperation.protea.core.training_dump._runner: top-level runner that coordinates the training-dump passes.protea.core.training_dump._test_split: helper that materialises the eval/test shard of the frozen dataset.protea.core.training_dump._train_split: helper that materialises the train shard of the frozen dataset.protea.core.operations._compute_embeddings_backends: backend dispatch logic for thecompute_embeddingscoordinator.protea.core.operations._compute_embeddings_helpers: batch construction and progress helpers forcompute_embeddings.protea.core.operations._embedding_pass_group: decides which embedding configs may be computed from ONE forward pass, and refuses the groups that may not.protea.core.operations._load_ontology_helpers: OBO parsing helpers used byload_ontology_snapshot.protea.core.operations._predict_go_terms_adapter: adapter that routes thepredict_go_termscoordinator to the unified-path or batch-op implementations.protea.core.operations.predict_go_terms._aspect_helpers: per-aspect splitting and merging helpers for the predict pipeline.protea.core.operations.predict_go_terms._batch_op: batch operation executed byOperationConsumerworkers.protea.core.operations.predict_go_terms._batch_op_feature: feature generation phase of the batch operation.protea.core.operations.predict_go_terms._batch_op_reference: reference-embedding loading and KNN search for batch operations.protea.core.operations.predict_go_terms._batch_op_reranker: reranker scoring phase of the batch operation.protea.core.operations.predict_go_terms._common: shared types and constants used across the predict-go-terms subpackage.protea.core.operations.predict_go_terms._coordinator: coordinator that partitions the query set and dispatches batch messages.protea.core.operations.predict_go_terms._post_knn_pipeline: post-KNN pipeline steps (feature enrichment, reranker, aggregation).protea.core.operations.predict_go_terms._reranker_scorer:RerankerScorercompositive class that applies a loaded booster to batch prediction DataFrames.protea.core.operations.predict_go_terms._store: bulk-insert helpers for writingGOPredictionrows.protea.core.operations.predict_go_terms._unified_path: unified in-process execution path used when a single worker handles both KNN and write phases.protea.core.operations._run_cafa_artifacts: artifact download and staging helpers forrun_cafa_evaluation.protea.core.operations._run_cafa_data_helpers: data-loading helpers for the CAFA evaluation pipeline.protea.core.operations._run_cafa_eval_driver: driver that callscafaeval.cafa_evaland collects per-namespace results.protea.core.operations._run_cafa_helpers: shared helper functions used across the_run_cafa_*modules.protea.core.operations._run_cafa_reranker_loader: loads and applies the reranker model to CAFA prediction TSVs.protea.core.operations._run_cafa_setup: environment and directory setup for a CAFA evaluation run.protea.core.operations._run_cafa_summary: summarises cafaeval results intoEvaluationResultrows.
Anc2Vec GO-term embedding index — thin shim over protea_method.anc2vec.
The implementation lives in the standalone protea-method library
(F2C extraction, 2026-05-07). This module is a backwards-compatible
shim so existing PROTEA call sites that import from
protea.core.anc2vec_embeddings keep working without changes; new
code should import directly from protea_method.anc2vec.
Path resolution (priority order)#
The Anc2Vec npz artefact is resolved through two mechanisms, in order:
Env var
PROTEA_ANC2VEC_PATH: if set and points to an existing readable file, that path wins. This is the recommended deploy configuration; the deploy runbook copies the artefact into the worktree and sets this variable.Repo-relative fallback: the historical
Path(__file__).resolve().parents[2] / "artifacts" / "anc2vec" / "anc2vec_2020-10.npz"location. The first time this branch is taken in a process a one-line warning is emitted suggestingPROTEA_ANC2VEC_PATHinstead.
Note: the anc2vec npz is a static pre-trained model artefact. It is
not managed as a Dataset
row (those track re-ranker training exports). There is therefore no
artifact-store resolution path for this file; use PROTEA_ANC2VEC_PATH
or the repo-relative fallback.
When both mechanisms fail (typical on a fresh deploy worktree where
artifacts/ is gitignored) a FileNotFoundError is raised
that lists both mechanisms so the operator can pick the right fix.
The repo-relative path stays exported as _DEFAULT_PATH for
backwards compatibility with code that imported the constant directly.
- class protea.core.anc2vec_embeddings.Anc2VecIndex(path: str | Path | None = None)#
Bases:
objectIn-memory lookup table for Anc2Vec GO-term embeddings.
- batch(go_ids: list[str], *, zero_if_missing: bool = True) numpy.ndarray#
Return an
(N, dim)matrix; missing rows zero (or NaN if disabled).
- dim#
- embeddings#
- go_ids#
- release#
- vec(go_id: str) np.ndarray | None#
Return the embedding for
go_idorNonewhen unknown.
- protea.core.anc2vec_embeddings.get_index(path: str | None = None) Anc2VecIndex#
Return a process-wide singleton index keyed by path.
Resolves the default path through env var > repo-relative fallback when no path is passed. See the module docstring for the full contract and operator-facing failure mode.
Process-local string interning for annotation hot loops.
The predict / train pipelines build millions of per-row dicts of the
shape {"go_term_id": int, "qualifier": str|None, "evidence_code": str|None}
when they materialise annotations from PostgreSQL. SQLAlchemy returns
each qualifier and evidence_code as a fresh Python string —
even though across a million rows there are only ~5-10 distinct values
("IEA", "IDA", "EXP", "TAS", …) and most rows have
qualifier = None.
Without interning, each duplicate string allocates ~50 B in CPython, so a 5 M-row batch can carry ~500 MB of redundant string objects. Interning collapses every duplicate to a single shared instance, a Flyweight-style intrinsic-state share. Python already does this implicitly for short identifier-like literals; this module forces the same dedup for the strings that come back from the DB driver.
Process-local by design (one cache per worker), trivially small (the
domain has fewer than 50 distinct codes/qualifiers in practice), and
thread-safe via the GIL — setdefault is atomic for built-in dicts.
- protea.core.annotation_intern.intern_string(value: str | None) str | None#
Return a shared instance of
valueif it has been seen before.Pass
Nonethrough unchanged so callers don’t need a guard. The pool grows monotonically; reset only when the worker restarts.
- protea.core.annotation_intern.pool_size() int#
Diagnostic — how many distinct strings the pool has retained.
On-disk caches for the predict_go_terms pipeline.
The reference embedding pool for an (EmbeddingConfig, AnnotationSet)
pair is large (millions of rows × ~1280 dims × 2 bytes = several GB).
Re-fetching it from PostgreSQL on every batch worker is the main
bottleneck, so the pool is materialised once into data/ref_cache/
and read back via numpy mmap on subsequent runs. Annotations are stored
in a CSR-style layout (offsets + flat go_term_ids /
qualifiers / evidence_codes arrays) so per-protein lookups stay
O(1) instead of dictionary-of-list-of-dict.
Files (under _DISK_CACHE_DIR):
{cfg}__{ann}_embeddings.npy— float16 reference embeddings{cfg}__{ann}_accessions.npy— aligned accession list{cfg}__{ann}__{aspect}_indices.npy— int32 indices into the unified pool{cfg}__{ann}__{aspect}_anno_*.npy— CSR annotation arrays
Invalidation: AnnotationSet rows are immutable once loaded, so the
cache stays valid for as long as the files exist. Delete the files
manually to force a reload after a model change.
- class protea.core.disk_cache.RefPoolKey(embedding_config_id: uuid.UUID, annotation_set_id: uuid.UUID, donor_discriminator: str = '')#
Bases:
NamedTupleThe triple that identifies one cached reference pool.
The two IDs say which embeddings and which annotations the pool was built from; the discriminator says under which donor policy it was built. All three change what the pool CONTAINS, so all three belong to its identity and none of them may travel without the others.
Bundling them is what keeps that true. While they were three loose arguments it was possible, and it happened, to thread the policy through the read path and forget the write path, which stores a filtered pool under the unfiltered name. It also keeps the loader under the master-plan section 3 six-parameter ceiling.
The discriminator defaults to the permissive policy’s empty string, so call sites that predate policies keep their historical key.
- annotation_set_id: UUID#
Alias for field number 1
- donor_discriminator: str#
Alias for field number 2
- embedding_config_id: UUID#
Alias for field number 0
V6 feature enrichment — shim + DB-bound helpers.
The pure-compute v6 pipeline lives in protea_method.feature_enricher
(F2C extraction, 2026-05-07). This module wraps it for callers that
pass a SQLAlchemy Session: enrich_v6_features here loads
go_id_map / go_aspect_map from the database and forwards them
to the library function. The DB-bound helpers
(_load_go_term_metadata, load_parent_map) and the local
ancestor-expansion helper (expand_predictions_to_ancestors,
which is pure compute but PROTEA-internal) stay here.
- class protea.core.feature_enricher.AncestorLabelConfig(gt_pairs: set[tuple[str, str]] | None = None, column: str = 'label', present: bool = False)#
Bases:
NamedTupleCaller-supplied label-injection knobs for ancestor expansion.
The training-dump path passes a populated
gt_pairsset so synthetic ancestor rows get a 0/1 label; the livepredict_go_termspath uses the empty default and skips label injection. The per-queryLabelConfig(withq_acc) is built internally per group.- column: str#
Alias for field number 1
- gt_pairs: set[tuple[str, str]] | None#
Alias for field number 0
- present: bool#
Alias for field number 2
- protea.core.feature_enricher.enrich_v6_features(predictions: list[dict[str, Any]], *, session: Session, ctx: KnnEnrichmentContext, compute_taxonomy: bool) None#
Compute the 25 v6 features and merge them into each
preddict in place.PROTEA-side wrapper around
protea_method.feature_enricher.enrich_v6_features: collects the GO term ids in play, loads the metadata maps from the database, and forwards everything to the library function. The library does the Anc2Vec pool, neighbor centroids, tax voters, PCA projection, and per-row merge.
- protea.core.feature_enricher.expand_predictions_to_ancestors(predictions: list[dict[str, Any]], *, parent_map: dict[str, set[str]] | dict[str, list[str]], k_limit: int, ia_weights: dict[str, float] | None = None, labels: AncestorLabelConfig = (None, 'label', False)) list[dict[str, Any]]#
Expand each leaf prediction to its is_a / part_of ancestor closure.
Mirrors the in-loop expansion in
protea.core.training_dump_helpers._knn_transfer_and_labelso the livepredict_go_termspath and the offline dump helper share a single canonical implementation.Per
(protein_accession, aspect)group, ancestor go_ids merge into existing leaves (bumping vote / min-distance) or land as synthetic rows that clone the closest leaf and overridego_id.labelscarries the training-dump-only (gt_pairs, column, present) triple; the live path leaves the default.
- protea.core.feature_enricher.load_parent_map(session: Session, snapshot_id: UUID) dict[str, set[str]]#
{child_go_id: {parent_go_id, ...}}for is_a + part_of edges in a givenOntologySnapshot. Used by the ancestor-expansion helper above; both the livepredict_go_termspath and offlinethe dump helpershould load it through this function so the closure they pass toexpand_predictions_to_ancestors()is identical.
Process-shared PCA state cache — thin shim over protea_method.pca_cache.
The implementation lives in the standalone protea-method library
(F2C extraction, 2026-05-07). This module is a backwards-compatible
shim so existing PROTEA call sites that import from
protea.core.pca_cache keep working without changes; new code
should import directly from protea_method.pca_cache.
The PROTEA-specific default artifact directory
(protea/artifacts/pca/) is preserved; the underlying helper
accepts an explicit artifacts_dir kwarg so the path stays under
the PROTEA repo regardless of CWD.
Anc2Vec feature-pre-computation phases for the KNN runner.
Extracted from _knn_transfer_runner._KnnTransferRunner (T2B.5
partial #8) to keep the runner class under the §3 500-LOC ceiling.
The three phases here build the shared Anc2Vec projection pool and
the per-(q, aspect) and per-query centroids that the leaf-record
builder consumes downstream.
Stateless apart from the runner back-reference; all reads / writes
go through self.runner attributes so the runner remains the
single source of truth for cross-phase state.
Per-group helpers extracted from expand_predictions_to_ancestors.
The ancestor-expansion loop in feature_enricher mutates either an
existing leaf record (when an ancestor coincides with a sibling leaf
prediction) or a synthetic ancestor record (cloned from the leaf with
go_id overridden). Both branches were inlined in the orchestrator,
pushing it well past the master plan v3.2 §3 method-LOC ceiling. This
module hosts the two branch helpers + the small label-config bundle so
the orchestrator can stay readable and short.
- class protea.core._feature_enricher_helpers.LabelConfig(q_acc: str, gt_pairs: set[tuple[str, str]] | None, column: str, present: bool)#
Bases:
NamedTupleBundle for the per-query label-injection knobs.
Carries the query accession (used as half of the
(q_acc, anc)ground-truth lookup) plus the optionalgt_pairsset and the column / presence flags that drive whether a synthesized ancestor record should carry a label at all. The training dump path passes a populated set; the livepredict_go_termspath leavesgt_pairsasNoneandpresentasFalse.- column: str#
Alias for field number 2
- gt_pairs: set[tuple[str, str]] | None#
Alias for field number 1
- present: bool#
Alias for field number 3
- q_acc: str#
Alias for field number 0
- protea.core._feature_enricher_helpers.compute_ia_weight(anc_gid: str, leaf_gid: str, ia_weights: dict[str, float] | None) float#
Weight contributed by
leaf_gidto its ancestoranc_gid.Without IA weights every edge counts as 1.0. When weights are provided, the contribution is the IA ratio anc/leaf (with a guard against zero-weight leaves to avoid division blow-ups when an incomplete IA file leaves a term at IA=0).
- protea.core._feature_enricher_helpers.compute_lineage_into(records: list[dict[str, Any]], *, parents: dict[str, list[str]], known: set[str], cache: dict[str, frozenset[str]]) None#
Write the 4
lineage_*columns into each record in place.Mirrors
protea_method.lineage.compute_lineage_featuresexactly but takes a caller-ownedcachereused across every per-(query, aspect) call (the library rebuilds it per call). Ancestor closures are split-invariant for a fixedparentsmap, so cache reuse is byte-identical to the library while collapsing the repeated BFS walks profiling flagged as a hot leaf (compute_lineage_features+_ancestor_closure, ~8% of build_records). Lazy import keeps the GO-DAG dependency out of the import graph for unrelated unit tests.
- protea.core._feature_enricher_helpers.make_ancestor_closure(parent_map: dict[str, set[str]] | dict[str, list[str]] | None) Callable[[str], frozenset[str]]#
Return a memoized
go_id -> ancestor closurecallable.The orchestrator calls the result repeatedly for every leaf GO id; caching is_a / part_of closures here keeps the inner loop O(1) after the first visit.
parent_mapis normalised tofrozensetparents up front so subsequent traversal cannot accidentally mutate the caller’s dict.
- protea.core._feature_enricher_helpers.merge_into_existing_leaf(leaf_anc: dict[str, Any], leaf_rec: dict[str, Any], vote_increment: float, leaf_d: float) None#
Fold a leaf-as-ancestor vote into the existing leaf candidate.
Called when the ancestor of a leaf prediction is itself already a leaf candidate for the same
(protein, aspect)group. Bumps the target’sneighbor_vote_fractionand lowers itsneighbor_min_distanceif the contributing leaf is closer.
- protea.core._feature_enricher_helpers.update_synth_entry(synth: dict[str, dict[str, Any]], anc: str, leaf_rec: dict[str, Any], leaf_d: float, vote_increment: float, label_ctx: LabelConfig) None#
Insert or update a synthetic ancestor record.
When the ancestor is not already a leaf candidate the record is fabricated from the closest contributing leaf. If a synthetic entry already exists, the closer leaf wins the per-pair feature payload (alignment, taxonomy, anc2vec, emb_pca) so the booster sees a consistent training-time view; otherwise only the vote fraction is bumped.
Per-feature compute bindings for the canonical FeatureRegistry (T2B.2).
T2B.1 populated protea.core.features.registry with placeholder
compute callables that raise NotImplementedError. This
module wires each feature in protea_contracts.ALL_FEATURES to
the legacy producer function it is filled by in the current code path
and calls CanonicalFeatureRegistry.bind_compute() once at
import time to replace the placeholders.
Mapping (family group -> producer):
KNN-derived columns (
distance,vote_count,k_position,go_term_frequency,ref_annotation_density,neighbor_distance_std,neighbor_vote_fraction,neighbor_min_distance,neighbor_mean_distance) come from the per-aspect record builder driven byprotea.core._knn_transfer_runner._KnnTransferRunner. They are bound to_knn_record_producer(), a marker callable that carries a reference to the runner on its__protea_producer__attribute.NW / SW alignment columns and
length_query/length_refcome fromprotea.core.feature_engineering.compute_alignment()(called per (query, ref) pair in_knn_transfer_runner).Taxonomy pair columns (
taxonomic_distance,taxonomic_common_ancestors,taxonomic_relation) come fromprotea.core.feature_engineering.compute_taxonomy().The v6 enrichment columns (
tax_voters_*,go_term_frequencyshare,anc2vec_*,emb_pca_query_*) come fromprotea.core.feature_enricher.enrich_v6_features().Lineage columns (
lineage_is_ancestor_of_known,lineage_is_descendant_of_known,lineage_ancestor_of_count,lineage_descendant_of_count) come fromprotea_method.lineage.compute_lineage_features(). Added in T-RES.1 to consume the lineage feature family registered byprotea-contractsv0.3.0.Categorical metadata (
qualifier,evidence_code,aspect) is sourced from annotation rows during record construction; the marker_annotation_metadata_producer()carries that intent.
The bound compute callables are not invoked by parquet_export
(the exporter reads pre-computed shards from disk). They exist so
that any downstream consumer of the registry can introspect which
legacy function produces each column. The __protea_producer__
attribute makes that legacy reference machine-readable.
Idempotency: apply_canonical_bindings() is safe to call more
than once on the same registry. It walks every feature in
protea_contracts.ALL_FEATURES and rebinds, so a fresh
registry (after reset_canonical_registry()) is restored to
fully-bound state by re-importing this module’s public function.
- protea.core.features._bindings.apply_canonical_bindings(registry: CanonicalFeatureRegistry) int#
Bind every
ALL_FEATURESfeature onregistryto its legacy producer reference. Returns the count of features bound.Idempotent: rebinding an already-bound feature is a no-op (the underlying
CanonicalFeatureRegistry.bind_compute()replaces the callable without touching dtype / family).
Method Object for training_dump_helpers._knn_transfer_and_label.
Hosts the _KnnTransferRunner class (T2B.5 partial #8 refactor) so the
parent training_dump_helpers module stays under the §3 file-LOC ceiling.
The runner orchestrates KNN search + feature pre-computation + per-query
record building, delegating the per-(query, candidate) record dictionary
construction to _LeafRecordBuilder.
Public API: run_knn_transfer_and_label (called from the thin wrapper in
training_dump_helpers). The class itself is private to keep the
collaborator pair tightly coupled.
- protea.core._knn_transfer_runner.run_knn_transfer_and_label(session: Session, p: TrainRerankerAutoPayload, ctx: KnnTransferContext, *, sequence_context: SequenceContext | None = None, stream_output: StreamOutput | None = None) list[dict[str, Any]] | dict[str, Any]#
Public entry point: instantiate the runner and drive
run().
Per-(query, candidate) record builder collaborator for the KNN runner.
Extracted from _knn_transfer_runner._KnnTransferRunner (T2B.5 partial
#8) to keep both the runner class and the runner module under the §3
LOC ceilings. The builder is a stateless collaborator that reads the
runner’s pre-computed feature dictionaries and materialises the
per-(query, candidate-GO) record dict + ancestor expansion.
Design:
_LeafRecordBuilderholds a back-reference to its_KnnTransferRunnerso it can read attributes (rr_*,tax_*,idx_of_go,all_norm,has_emb_mask, …).Method signatures use the small
_LeafContext/_LeafInputsparameter objects defined in the runner module.
- protea.core._leaf_record_builder.build_classifier_only_record(builder: _LeafRecordBuilder, q_acc: str, go_id: str, aspect: str, score: float) dict[str, Any]#
Materialise one classifier-only candidate record (native pool-union).
Module-level twin of
_LeafRecordBuilder.make_interpro_only_record()(kept out of the class so the class stays under the §3 LOC ceiling). The classifier proposesgo_idfrom the query’s PLM embeddings, not from a KNN neighbour, so this row carries no KNN / alignment / taxonomy / Anc2Vec / emb_pca evidence: every such column is NaN (LightGBM reads it as missing), matching the distribution the predict path’s_new_classifier_recordserves at inference. Only the classifier family is real (classifier_score/classifier_present1.0); the self_prior / association columns stay at the zero-fill default until the per-query parity producers run over the unioned record list. Carries the FULL canonical column set so the T1.8 parquet boundary holds, and gets the SAME(protein, go_id)GT label downstream the KNN rows do (a leakage-free placeholder, re-applied per category by the train / test split labelers).
Parallel + persistent computation of per-pair alignment features.
The export pipeline’s hotspot is the per-(query, reference) alignment in
_KnnTransferRunner._compute_pair_features: a single-threaded triple
loop calling compute_alignment (parasail NW+SW with traceback) at a
few hundred pairs/s. Two structural wins live here:
Process-level parallelism over the unique alignment pairs. parasail’s traceback variants do not release the GIL well enough for threads to scale, so a
ProcessPoolExecutoris used (benchmarked ~3x on a 12-core box). The taxonomy lookups stay in the parent process because they are cheap (anlru_cacheover ete3 lineages) and process re-init of the ete3 sqlite handle would dwarf the work.A persistent on-disk cache keyed by the ordered sequence pair plus the alignment parameters. Intra-PLM the K=10 neighbour set is a superset of K=5 / K=3, so alignments computed once for the largest-K dataset make the smaller-K datasets (and any re-run) near-free.
protea.trainingis serialised (one job at a time) so there is no concurrent-write contention; a plain sqlite file is enough.
This module is value-preserving by construction: the alignment feature
dict it returns is exactly what compute_alignment returns, only
computed concurrently and memoised. Disabling parallelism (workers <= 1)
and the cache (PROTEA_ALIGN_CACHE_DIR unset / cache-miss) reduces to
the original serial code path.
- class protea.core._pair_feature_compute.PairAlignmentComputer#
Bases:
objectCompute alignment-feature dicts for many pairs, cached + parallel.
Use as a context manager so the sqlite handle and process pool are released deterministically.
- compute(pairs: list[tuple[str, str]]) dict[tuple[str, str], dict[str, Any]]#
Return
{(q_seq, r_seq): alignment_dict}for every input pair.Empty-sequence pairs are skipped by the caller; here every pair is assumed to have two non-empty sequences. Deduplicates on the ordered sequence pair so identical pairs are aligned once.
- protea.core._pair_feature_compute.build_pair_feature_dict(q_acc: str, ref_acc: str, align_by_pair: dict[tuple[str, str], dict[str, Any]], *, do_alignments: bool, do_taxonomy: bool, tax_ids: tuple[dict[str, Any] | None, dict[str, Any] | None]) dict[str, Any]#
Merge the precomputed alignment + per-pair taxonomy for one pair.
Value-identical to the original inline
compute_alignment+compute_taxonomymerge: the alignment half is looked up from the batch-computed map, the taxonomy half is computed here (cheap,lru_cache-backed). Either family is skipped when its flag is off.
- protea.core._pair_feature_compute.precompute_alignment_features(*, aspects: Sequence[str], neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]], valid_queries: Sequence[str], query_sequences: dict[str, str], ref_sequences: dict[str, str]) dict[tuple[str, str], dict[str, Any]]#
Batch-align every unique (q_acc, ref_acc) neighbour pair.
Drives
PairAlignmentComputer(parallel + on-disk cache) over the deduplicated pair set and remaps the result back onto the(q_acc, ref_acc)accession keys the runner indexes by. Returns an empty map when there are no alignable pairs.
- protea.core._pair_feature_compute.resolve_workers() int#
Number of process-pool workers for pair-feature computation.
PROTEA_PAIR_FEATURE_WORKERSoverrides; default is the CPU count. A value <= 1 forces the serial path (no pool spin-up).
Bulk DB loaders extracted out of training_dump_helpers.
Three private helpers used by the dump pipeline:
_count_embeddings_with_dim(): single COUNT +vector_dimsprobe for a given embedding-config UUID._stream_embeddings(): pre-allocatednp.emptymatrix filled viayield_perover thesequence_embeddingjoin._load_annotation_aggregations(): per-aspect grouping of annotation rows under the GOP/F/Caspects, filtering against a providedacc_to_idxso only proteins with a preloaded embedding contribute to the reference set.
All three are intentionally I/O-only: they take a SQLAlchemy
Connection (already opened by the caller) and return plain Python /
NumPy structures. Keeping them out of training_dump_helpers lets
_preload_all_embeddings and _build_reference_from_cache stay
under the §3 60-LOC method ceiling without the dump-helper file
ballooning further.
Shared constants for the dump pipeline submodules.
Kept here so the split helpers, the test-split helpers, and the runner can share them without forming an import cycle (T2B.6).
Parameter objects for the dump pipeline.
Originally lived in protea/core/training_dump_helpers.py. Extracted
to a leaf submodule (T2B.6) so the type-only consumers in
protea/core/_knn_transfer_runner.py can import them without
dragging the larger orchestration code into the import graph.
- class protea.core.training_dump._contexts.KnnTransferContext(valid_queries: list[str], query_emb: np.ndarray, ref_by_aspect: dict[str, dict[str, Any]], go_id_map: dict[int, str], aspect_map: dict[int, str], gt_pairs: set[tuple[str, str]], query_known_gos: dict[str, set[str]] | None = None, parent_map_str: dict[str, set[str]] | None = None, ia_weights: dict[str, float] | None = None, pca_state: tuple[np.ndarray, np.ndarray] | None = None, pivot_go_ids: set[str] | frozenset[str] | None = None, embedding_pool: np.ndarray | None = None, t0_annotation_set_id: uuid.UUID | None = None)
Bases:
objectBundle of KNN inputs + enrichment maps for
_knn_transfer_and_label.Groups the 12 per-call data arguments (queries, references, ontology maps, optional enrichment helpers) so the entry-point signature stays under flake8-bugbear’s parameter ceiling.
session, payloadp,sequence_context, andstream_outputremain standalone arguments because they are configuration / IO concerns, not data.- aspect_map: dict[int, str]
- embedding_pool: np.ndarray | None = None
- go_id_map: dict[int, str]
- gt_pairs: set[tuple[str, str]]
- ia_weights: dict[str, float] | None = None
- parent_map_str: dict[str, set[str]] | None = None
- pca_state: tuple[np.ndarray, np.ndarray] | None = None
- pivot_go_ids: set[str] | frozenset[str] | None = None
- query_emb: np.ndarray
- query_known_gos: dict[str, set[str]] | None = None
- ref_by_aspect: dict[str, dict[str, Any]]
- t0_annotation_set_id: uuid.UUID | None = None
- valid_queries: list[str]
- class protea.core.training_dump._contexts.SequenceContext(query_sequences: dict[str, str] | None = None, ref_sequences: dict[str, str] | None = None, query_tax_ids: dict[str, int | None] | None = None, ref_tax_ids: dict[str, int | None] | None = None)
Bases:
objectPer-protein sequence and taxonomy lookups.
All four attributes are optional; passing
Nonedisables the corresponding feature family (alignment / taxonomy).- query_sequences: dict[str, str] | None = None
- query_tax_ids: dict[str, int | None] | None = None
- ref_sequences: dict[str, str] | None = None
- ref_tax_ids: dict[str, int | None] | None = None
- class protea.core.training_dump._contexts.StreamOutput(output_parquet: Path, chunk_rows: int = 100000)
Bases:
objectStreaming parquet output for memory-bounded dataset generation.
When provided,
_knn_transfer_and_labelwrites labeled rows directly tooutput_parquetin chunks ofchunk_rowsinstead of accumulating the full result list in memory.- chunk_rows: int = 100000
- output_parquet: Path
Reference / sequence / taxonomy loaders for the dump pipeline.
Originally lived in protea/core/training_dump_helpers.py. Extracted
to a leaf submodule (T2B.6) so the orchestration code can import the
loaders without pulling in the entire split runner. Behaviour is byte
identical.
Thin facade over the _knn_transfer_runner Method Object.
Kept as a separate submodule (T2B.6) so the test-split and train-split helpers can import the entry point without each pulling the runner module into their import graph at top level.
Payload for the auto dump operation.
Originally lived in protea/core/training_dump_helpers.py. The model
shape is unchanged; only the file location moved (T2B.6).
- class protea.core.training_dump._payload.TrainRerankerAutoPayload(*, name: str, embedding_config_id: str, ontology_snapshot_id: str, train_versions: list[int], test_versions: list[int], evaluation_set_ids: list[str] = [], annotation_source: str = 'goa', limit_per_entry: Annotated[int, Gt(gt=0)] = 5, distance_threshold: float | None = None, search_backend: str = 'faiss', metric: str = 'cosine', faiss_index_type: str = 'IVFFlat', faiss_nlist: int = 256, faiss_nprobe: int = 32, num_boost_round: int = 1000, early_stopping_rounds: int = 50, val_fraction: float = 0.2, neg_pos_ratio: float | None = None, reranker_objective: str = 'binary', compute_alignments: bool = False, compute_taxonomy: bool = False, compute_anc2vec: bool = False, compute_self_prior: bool = False, compute_association: bool = False, compute_classifier: bool = False, compute_protst: bool = False, parity_chunk_size: int = 512, ia_file: str | None = None, expand_votes_to_ancestors: bool = False, use_embedding_pca: bool = False, training_scope: str = 'per_category', per_cell_min_positives: Annotated[int, Gt(gt=0)] = 200, dump_to: str | None = None, dump_only: bool = False, stable_feature_cache: bool = False, classifier_variants: list[dict[str, str]] | None = None)
Bases:
ProteaPayloadPayload for the dump_helper operation.
Generates consecutive temporal pairs from
train_versions, runs KNN once per pair, then trains 3 per-category LightGBM models (NK, LK, PK) and evaluates each on the held-out test split.- annotation_source: str
- classmethod at_least_one_test(v: list[int]) list[int]
- classmethod at_least_two_train(v: list[int]) list[int]
- classifier_variants: list[dict[str, str]] | None
- compute_alignments: bool
- compute_anc2vec: bool
Compute the two anc2vec families. False by default, and that default is a record rather than a choice: the index they need is produced by no registered operation, so on a host without the npz the phases raised FileNotFoundError at phase five, after the KNN and three feature passes had run. With the index absent the columns were never produced anyway. Asking for them without the artefact still raises – the flag gates the attempt, it does not invent the data.
- compute_association: bool
- compute_classifier: bool
- compute_protst: bool
- compute_self_prior: bool
- compute_taxonomy: bool
- distance_threshold: float | None
- dump_only: bool
- dump_to: str | None
- early_stopping_rounds: int
- embedding_config_id: str
- evaluation_set_ids: list[str]
WHICH declared window each pair’s truth comes from, by id. A SET of ids and not a list parallel to the pairs, because the pairs are generated from
train_versionsand a position nobody can check is a position that silently shifts.Empty is the old behaviour and still works wherever a pair has exactly one window. It does not work on this campaign: the three propagation graphs and the three truth rules are part of a window’s identity, so 62 of 69 distinct pairs already carry more than one, and the export refuses rather than guess. Naming is how a dump says which truth it trained on, which is the part that moves and the part a dataset could not previously record.
Every named window’s
pivot_snapshot_idhas to equalontology_snapshot_id: a window on another pivot expresses its truth on another term axis, and a manifest declaring one axis over windows using another is wrong about its own vocabulary.
- expand_votes_to_ancestors: bool
- faiss_index_type: str
- faiss_nlist: int
- faiss_nprobe: int
- ia_file: str | None
- limit_per_entry: PositiveInt
- metric: str
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str
- name: str
- neg_pos_ratio: float | None
- num_boost_round: int
- ontology_snapshot_id: str
- parity_chunk_size: int
- per_cell_min_positives: PositiveInt
- reranker_objective: str
- classmethod scope_is_valid(v: str) str
- search_backend: str
- stable_feature_cache: bool
- test_versions: list[int]
- train_versions: list[int]
- training_scope: str
- use_embedding_pca: bool
- val_fraction: float
Per-execution Method Object plus the public auto operation.
Extracted from protea/core/training_dump_helpers.py as part of
T2B.6. Behaviour is unchanged.
- class protea.core.training_dump._runner.TrainRerankerAutoOperation
Bases:
objectAutomated multi-split temporal holdout re-ranker training.
Trains 3 per-category models (NK, LK, PK) in a single execution. Each model trains on all aspects combined, giving it ~3x more data than per-aspect models and better convergence.
Pipeline:
Resolve annotation set IDs from version numbers.
Load GO maps once; optionally load IA weights for sample weighting.
For each consecutive pair in
train_versions, compute the evaluation delta (all 3 categories at once), load references and query embeddings, run KNN + GO transfer, and label predictions against each category’s ground truth.For each category (NK, LK, PK), concatenate the labeled data from all splits, train one LightGBM model with optional IA sample weights, evaluate on the test split, and store a
RerankerModelas{name}-{category}.
- description = 'Run KNN + feature generation across multiple temporal holdout pairs and emit frozen parquets. Originally also trained LightGBM models; that path now lives in protea-reranker-lab.'
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult
- name = 'research_dataset_dump_helper'
- summarize_payload(payload: dict[str, Any], *, session: Session | None = None) str
Test-split helpers for the dump pipeline.
Originally part of protea/core/training_dump_helpers.py. Extracted
(T2B.6) so the split phase modules stay under the file-LOC ceiling.
Behaviour is unchanged; the helpers still mutate the orchestrator’s
test_files map in place where they did before.
Train-split helpers for the dump pipeline.
Mirror of the test-side helpers in _test_split but for the per-pair
training loop. Each helper covers one phase of the per-iteration body
so the orchestrator stays under the §3 60-LOC method ceiling. Several
helpers reuse the test-side bundles (_TestQueryInputs,
_TestSequences) and pure functions (_compute_test_cat_membership,
_load_test_sequences_and_taxonomy) since the data shape is
identical between sides; a follow-up renames them generically.
Like the test side, predictions are streamed to an intermediate parquet
(StreamOutput) and read back in pyarrow batches to write the
per-category labeled shards. That keeps peak memory at roughly one batch
instead of the previous list-of-dicts + DataFrame materialisation (which
peaked near 95 GB on the largest snapshot pairs).
Per-PLM backend implementations extracted from compute_embeddings.
This sibling module hosts the four embed-function families (ESM,
T5, Ankh, ESM3c) and the shared layer / pooling / chunking helpers
they all build on. The dispatch registry + plugin loader stay in
compute_embeddings.py; this file only contains pure forward-pass
+ pooling code.
The ChunkEmbedding data container is now sourced from
protea_backends._chunk_helpers (T2A.5b consolidation) so the
plugin-returned value (list[ChunkEmbedding] produced by
plugin.embed_chunks) and any PROTEA-local construction share a
single class identity. PROTEA re-exports it from here and from
compute_embeddings for backwards-compatible imports.
The four _embed_* functions are retained as the bit-exact
parity reference for the plugin ports (see
tests/test_compute_embeddings_backend_dispatch.py) and are
re-exported from compute_embeddings so the documented
unittest.mock.patch("protea.core.operations.compute_embeddings._embed_*")
test pattern keeps working unchanged.
- class protea.core.operations._compute_embeddings_backends.ChunkEmbedding(chunk_index_s: int, chunk_index_e: int | None, vector: numpy.ndarray.(typing.Any, typing.Any))
Bases:
objectOne pooled embedding for a contiguous residue span of a sequence.
chunk_index_sandchunk_index_euse the same convention as the PROTEA DB columns: start is 0-based inclusive, end is exclusive. When chunking is disabled,chunk_index_s=0andchunk_index_e=None(full sequence).- chunk_index_e: int | None
- chunk_index_s: int
- vector: numpy.ndarray.(typing.Any, typing.Any)
Pure helpers extracted from compute_embeddings operation classes.
Keeps the operation file (compute_embeddings.py) under the master
plan v3.2 §3 method-LOC ceiling while leaving the operation classes
focused on payload validation, model loading, and the publish path.
- protea.core.operations._compute_embeddings_helpers.build_batch_dispatch_messages(p: ComputeEmbeddingsPayload, parent_job_id: uuid.UUID, sequence_ids: list[int], lengths: dict[int, int] | None = None) list[tuple[str, dict]]
Partition sequences into per-job batches and build their queue messages.
Coordinator-side helper for
ComputeEmbeddingsOperation.execute: splits the fullsequence_idslist into chunks ofp.sequences_per_joband emits onecompute_embeddings_batchmessage per chunk addressed to the GPU batch queue. The messages carry every payload field that the child workers need (no DB lookups happen between coordinator and worker), including the whole config group: one message runs one forward pass and serves all of them.lengthsis only read when the payload asks for isolation; seepartition_sequence_ids(), which is where the partition is decided.
- protea.core.operations._compute_embeddings_helpers.build_embedding_rows(session: Session, config_id: UUID, sequences: list[dict[str, Any]], skip_existing: bool) tuple[list[dict], int, int, int]
Materialise SequenceEmbedding insert rows for ONE config of a store batch.
Iterates
sequencesand skips entries whose(sequence_id, config_id)pair already exists whenskip_existingis true; otherwise deletes the existing rows so the bulk insert can replace them. Each stored vector is divided by THIS config’s uniformembedding_scaleand clipped to the fp16 halfvec range (seescale_and_clip_embedding());scale == 1.0(the default) is a no-op. Returns(rows, embeddings_stored, sequences_skipped, components_clipped); callers run the bulk insert, emit a WARN whencomponents_clippedis non-zero, and update per-job progress.
- protea.core.operations._compute_embeddings_helpers.build_store_message(parent_job_id: uuid.UUID, p: ComputeEmbeddingsBatchPayload, per_config: list[tuple[str, list[dict]]]) tuple[str, dict]
Build ONE write-queue message carrying every config the pass served.
One message rather than one per config, because the write has to be all or nothing. A batch that stored config A and then failed on B would leave the group at unequal coverage, which is the bank imbalance this fan-out exists to remove, arriving by the back door: spread irregularly across eleven configs with similar-looking counts instead of showing up as one visible gap. One message is one
store_embeddingsexecution and so one transaction.It also keeps the parent’s
progress_totalcounting batches, as it always has: one batch, one write, one increment.
- protea.core.operations._compute_embeddings_helpers.clean_config_ids(value: Any) Any
Validate a config group: a non-empty list of non-empty, stripped strings.
- protea.core.operations._compute_embeddings_helpers.config_group_keys(config_ids: list[str]) dict[str, Any]
Name a config group in the payload shape its consumer can actually read.
One config is written in the legacy singular shape so a worker running code older than this change still does exactly the right work. More than one is written in the plural shape precisely so that worker REFUSES: a stale consumer silently dropping the key it does not declare would embed one layer of a group of three, store it, and report the job succeeded. That is the version-skew failure
ProteaPayload’sextra="forbid"exists to turn into a loud one, and it only stays loud if the new shape is on the wire.
- protea.core.operations._compute_embeddings_helpers.fetch_embedding_scale(session: Session, config_id: UUID) float
Return the owning config’s uniform
embedding_scale(constant per config).Defaults to
1.0(no-op) for a missing config or a missing/zero value, so every existing config keeps its byte-for-byte store behaviour.
- protea.core.operations._compute_embeddings_helpers.fold_legacy_store_groups(data: Any) Any
Fold a one-config store payload into the
groupslist.The write worker used to be told one config and one list of sequences. It is now told a whole group, so a message published by a worker running older code (or sitting in the queue across a deploy) still has to validate: its
embedding_config_idandsequencesbecome a single group.
- protea.core.operations._compute_embeddings_helpers.missing_for_any_config(config_ids: list[UUID]) Any
A
skip_existingpredicate: keep a sequence ANY config in the group lacks.One pass serves the whole group, so the sequence is still needed as long as a single config has no row for it. Intersecting instead (keep it only when EVERY config lacks it) would leave the newest layer of a grid unembedded for every sequence an older layer already held, and the job would report success having written nothing for it. With one config this is the
NOT EXISTSthe coordinator has always filtered on.
- protea.core.operations._compute_embeddings_helpers.normalise_config_ids(data: Any) Any
Fold the legacy singular
embedding_config_idinto the plural field.Twelve historical jobs are on record carrying
embedding_config_idas a bare string, and they have to keep validating exactly as they did, so the field cannot simply be renamed. The fold happens here, before pydantic looks at the keys, becauseProteaPayloadforbids extras: a legacy key left in place would be refused rather than ignored.Carrying both keys is a refusal and not a merge. Reconciling them would take a rule nobody has written down, and the group a worker ended up computing would then depend on which version of that rule its code happens to hold.
- protea.core.operations._compute_embeddings_helpers.scale_and_clip_embedding(vector: list[float], scale: float) tuple[list[float], int]
Divide a per-sequence embedding by
scaleand clip it to the fp16 range.Returns
(scaled_vector, n_clipped).scale == 1.0(the default for every existing config, including the champion) is a pure passthrough: the exact input list object is returned unchanged, so no numpy round-trip and no clip can perturb those values. For any non-default scale the vector is divided uniformly, then clipped to[-65504, 65504]as a safety net so an over-small configured scale can never let an inf reach the halfvec column;n_clippedcounts how many components were clipped (a WARN signal that the scale was too small).A uniform per-config divisor is safe for every downstream consumer: cosine-KNN is scale-invariant and the per-dim z-score standardisation absorbs a uniform scale, so
embedding / scaleis equivalent to the raw embedding.
- protea.core.operations._compute_embeddings_helpers.serialize_inferred_chunks(sequences: list[Sequence], batch_chunks: list[list[ChunkEmbedding]]) list[dict]
Build per-sequence dicts the store_embeddings worker consumes.
Pairs each input
Sequencerow with its inferred chunk list and flattens eachChunkEmbeddinginto JSON-friendly fields. The write worker uses these dicts directly without re-fetching from the DB.The pairing is strict. It is positional, and the
sequence_idcomes from one side while the vectors come from the other, so a short inference result would not drop the tail: it would store one sequence’s embedding under a different sequence’s id. The write worker takes these dicts on trust, so nothing downstream would notice.
- protea.core.operations._compute_embeddings_helpers.store_group_rows(session: Session, p: StoreEmbeddingsPayload) dict[str, int]
Insert every config’s rows for one batch, in the caller’s single transaction.
The scale and the fp16 clip are resolved per config INSIDE the loop, not once for the message.
embedding_scaleis a property of the config that owns the rows, so hoisting it would store every config’s vectors divided by the first config’s scale: no error, no warning, just wrong magnitudes under right-looking ids.
- protea.core.operations._compute_embeddings_helpers.t5_forward_pass(model: Any, input_ids: Any, attention_mask: Any) Any
Run a T5 encoder forward pass under
no_grad; returnhidden_states.Lazy-imports
torchso this module stays importable on machines without it (e.g. the API process where embedding code is never exercised). Frees theoutputsreference and triggers a CUDA cache flush before returning so the caller can reuse the residual GPU memory for the per-sequence pool step.Pulled out of
_embed_t5to keep that backend entry point under the §3 60-LOC ceiling.
Which embedding configs may share one forward pass, and the refusal when they may not.
A forward pass already computes every hidden layer, unconditionally, in every
backend PROTEA ships: EsmModel.from_pretrained(..., output_hidden_states=True)
and model(**tokens, output_hidden_states=True) for ESM / T5 / Ankh,
LogitsConfig(return_hidden_states=True) for ESM-C. layer_indices never
asks the model for anything. It SELECTS, after the fact, from tensors that
already exist: protea_backends._chunk_helpers.validate_layers reduces it to
sorted({int(li) for li in layer_indices}) and indexes into the hidden
states it was handed.
ComputeEmbeddingsPayload nonetheless carried one config id, so a layer grid
was run as one job per layer. Eleven configs pending a bank match are eleven
LAYERS of four models (ankh-base [16] [32]; esmc_600m [12] [24] [35];
esm2_t33_650M [11] [22] [33]; prot_t5_xl [8] [16] [24]), which at the rates the
GPU node measured is 113.6 h of inference where 42.3 h of it is distinct work.
Ten of the eleven passes recompute tensors the first one already held.
The saving is only real if the group really does share a pass, and “really” has to be settled field by field rather than by eye, which is what this module is for. Grouping configs that do NOT share a pass would write vectors under config ids whose recipes never produced them: the rows would be well formed, the job would report success, and nothing downstream re-derives an embedding, so the mislabelling would never surface. That is why the check below RAISES rather than warning and carrying on with a default.
- protea.core.operations._embedding_pass_group.FORWARD_PASS_FIELDS: tuple[str, ...] = ('max_length', 'model_backend', 'model_name')
The substrate fields that decide what the model is fed and which weights read it. Two configs differing in any of them are two different forward passes, and no amount of sharing makes them one.
max_lengthbelongs here even though it reads like a post-processing bound: every backend truncates BEFORE the model sees the sequence (truncation=True, max_length=config.max_lengthin the ESM tokenizer call and in the T5 / Ankhbatch_encode_plus;seq_str[: config.max_length]in ESM-C). A shorter bound is a shorter input, so it is a different pass.model_namebelongs here for the weights and for a second reason that is easy to miss: the T5 backend auto-detects ProstT5 from the model name and prepends<AA2fold>. Two names can therefore differ in the TOKENS as well as in the parameters.
- protea.core.operations._embedding_pass_group.REDUCTION_ONLY_FIELDS: tuple[str, ...] = ('chunk_overlap', 'chunk_size', 'layer_agg', 'layer_indices', 'normalize', 'normalize_residues', 'pooling', 'use_chunking')
The substrate fields that are read strictly after
hidden_statesexists, and may therefore differ inside one group. Each one was traced to its use rather than assumed:layer_indices– pure selection; see the module docstring. This is the axis the whole change exists to fan out over.layer_agg–aggregate_layersreduces across the tensors that selection already returned.pooling– collapses residues to a vector. Theclsbranch looks like a different pass but is not: it reads position 0 of the same hidden states.normalize_residues/normalize– L2 applied to the residue matrix and to the pooled vector respectively, both after the pass.use_chunking/chunk_size/chunk_overlap–chunk_and_poolslices spans out of the POST-pass residue tensor. Chunking here is not a windowed re-inference; the model is never run again per chunk.
- exception protea.core.operations._embedding_pass_group.SharedForwardPassError
Bases:
ValueErrorRaised when a config group would not, in fact, share one forward pass.
A
ValueErrorsubclass so a worker treats it as a hard, non-retryable failure like every other bad-payload refusal on this path, while callers that want to distinguish it can.
- protea.core.operations._embedding_pass_group.WRITE_ONLY_FIELDS: tuple[str, ...] = ('embedding_scale',)
they are applied when the vector is written.
embedding_scaleis a property of the config that owns the rows, resolved per config insidestore_group_rows.- Type:
Fields that are neither fed to the model nor read during the reduction
- protea.core.operations._embedding_pass_group.assert_layers_available(configs: list[Any], model: Any) None
Refuse a layer index the loaded model does not have, BEFORE the first pass.
protea_backends._chunk_helpers.validate_layersis handedhidden_states, so it can only raise once the forward pass has already run. With one config that cost a batch; with a group it costs the whole pass for every config in it, and the third config asking for a layer the model does not have kills a job that has already paid the card. Checking against the depth the loaded model DECLARES moves that failure to just after the load, where it is free.A model whose depth cannot be read is left to
validate_layers: this is a pre-flight that makes the existing check earlier, never one that replaces it, so an unreadable depth degrades to today’s behaviour rather than to silence.
- protea.core.operations._embedding_pass_group.assert_shared_forward_pass(configs: list[Any]) None
Refuse a config group whose members do not share one forward pass.
Every field in
FORWARD_PASS_FIELDSmust be identical across the group; every field inREDUCTION_ONLY_FIELDSmay vary.The message names EVERY diverging field with its distinct values, not the first one found. A group differing in two fields reported as differing in one invites the caller to fix that one, re-dispatch, and be refused again for a reason that was already known: the same defect as describing a level by one of the fields that vary in it.
- protea.core.operations._embedding_pass_group.load_pass_group(session: Session, config_ids: list[str]) list[EmbeddingConfig]
Load a config group in payload order, refusing a missing id or a bad group.
Both the coordinator and the batch worker call this. The coordinator so a bad group dies before any GPU time is spent on it; the batch worker because it is handed config ids on a queue and is the process that would actually write the mislabelled rows, and a guard that only runs upstream is a guard the message that skipped the coordinator never meets.
- protea.core.operations._embedding_pass_group.run_group_inference(embed_group: Callable[[list[str]], list[list[ChunkEmbedding]]], configs: list[EmbeddingConfig], sequences: list[Sequence], batch_size: int, load_s: float) tuple[list[tuple[str, list[dict]]], dict[str, float]]
Batch
sequences, embed each batch for the whole group, and pair up the rows.embed_grouptakes the batch’s sequence strings and returns one chunk-list-per-sequence for each config, in the group’s order; the operation supplies it so the model, device and dispatch seam stay where they are.Returns
([(config_id, write_sequences), ...], phase_timings). The pairing is positional on both axes andstrict=Trueon both, because both are silent when they go wrong: a short outer list would attribute one config’s vectors to the next config in the group, and a short inner one would attribute one sequence’s vectors to the next sequence (the failureserialize_inferred_chunksalready refuses).inference_sis the number to watch as configs are added to a group: the forward pass is 99.51% of wall clock, so it is what has to stay flat for the saving to be real, and it is measured here rather than projected.
- protea.core.operations._embedding_pass_group.shared_pass_emitter(config: EmbeddingConfig) Any | None
The backend’s
embed_chunks_multi, orNonewhen it has none.The reduction side of this fan-out is PROTEA’s; the pass side is the plugin’s, because only the plugin holds the hidden states and
protea-backendsis a separately pinned dependency. Resolved bygetattrrather than declared on the plugin protocol, so PROTEA does not need a lockstep bump of that pin to land the contract and a fleet part-way through the bump degrades to correct N-pass work rather than raisingAttributeErroron every batch.The signature it must satisfy is
embed_chunkswith the config pluralised:(model, tokenizer, sequences, configs, device), returning onelist[list[ChunkEmbedding]]per config, in the order the configs arrived.
- protea.core.operations._embedding_pass_group.warn_if_pass_not_shared(configs: list[EmbeddingConfig], emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) None
WARN when a group of more than one is about to pay for a pass per config.
The group is still correct without the plugin-side emitter, which is exactly why it has to say so: a job that fanned out three configs and quietly ran three passes produces the same rows as one that ran one, and the only difference is the number this change exists to move. Silence there would let the saving be reported from the contract rather than from the clock.
The one place that turns UniProt records into protein and sequence rows.
WHY THIS MODULE EXISTS. Two operations need exactly this: insert_proteins,
which walks a release flat file, and resolve_protein_sequences, which asks
UniProt for the sequences the GAF-derived universe is missing. Until now the
second reached into the first’s private _store_records, with a comment
calling it “the lesser of two evils” and a test pinning the signature so the
coupling would break loudly. The evil was avoidable: the logic is a pure
function of (session, records), it names nothing about pagination or about a
GAF, and a module-level function is the shape the platform already uses for
shared domain logic (_load_ontology_helpers, _compute_embeddings_helpers).
WHAT IT GUARANTEES, and why both callers need the same guarantee.
Sequences are deduplicated by MD5. Several accessions can carry one sequence
– isoforms, merged entries, identical proteins across strains – and
sequence_id is deliberately non-unique on protein. Embeddings are keyed
on Sequence, not on Protein, so two accessions over one sequence cost ONE
embedding and contribute ONE neighbour to the KNN bank. A second copy of this
dedup would have been a second chance to get that wrong.
Existing rows are patched, never clobbered. apply_record_updates() fills
nulls, flips canonicality and refreshes the isoform index, and leaves every
non-empty value alone. This is what makes the two callers composable in either
order: extract_goa_universe inserts an accession with no sequence,
resolve_protein_sequences later fills the sequence and the audit dates on the
same row, and insert_proteins running over the same accession afterwards
neither duplicates it nor undoes either.
- class protea.core.operations._protein_store.StoreCounts(proteins_inserted: int = 0, proteins_updated: int = 0, sequences_inserted: int = 0, sequences_reused: int = 0)#
Bases:
objectWhat one
store_records()call did, by kind.A named object rather than the 4-tuple the private method returned. The tuple was the reason the old coupling could not fail loudly: a reordering of its members would have been silently wrong for hours, and only a test asserting “four integers” stood between that and a mislabelled run.
- add(other: StoreCounts) None#
- proteins_inserted: int = 0#
- proteins_updated: int = 0#
- sequences_inserted: int = 0#
- sequences_reused: int = 0#
- protea.core.operations._protein_store.apply_record_updates(p: Protein, r: UniProtProteinRecord, seq_id: int | None, *, asserts_reviewed: bool = True) bool#
Patch
pfromrwithout clobbering; returnTrueif anything changed.The null-filling is what lets the universe be built in two steps:
extract_goa_universewrites a row whosesequence_id,entry_name,organism,taxonomy_id,gene_nameandlengthare all NULL, and this fills every one of them when UniProt finally answers for it.
- protea.core.operations._protein_store.build_protein(r: UniProtProteinRecord, seq_id: int | None, *, asserts_reviewed: bool = True) Protein#
A new
Proteinrow from a UniProt record.
- protea.core.operations._protein_store.load_existing_proteins(session: Session, accessions: Sequence[str], chunk_size: int = 5000) dict[str, Protein]#
The
Proteinrows that already exist, keyed by accession.
- protea.core.operations._protein_store.store_records(session: Session, records: list[UniProtProteinRecord], emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None], *, asserts_reviewed: bool = True) StoreCounts#
Upsert
recordsassequence+proteinrows.asserts_reviewed=Falsesays the source cannot answer the Swiss-Prot question, soreviewedis left NULL instead of being filled from the record. UniParc is such a source: it keeps sequences, not entry status, and an accession it answers for is one UniProtKB no longer serves, so there is no status to read. WritingFalsethere would be indistinguishable from a TrEMBL entry UniProt actually called unreviewed, and NULL already means the thing that is true: nobody asked, or nobody could answer.Does NOT commit: the caller owns the transaction boundary, because the two callers want different ones –
insert_proteinscommits per page so an interrupted ingest leaves a partial-but-consistent dataset, andresolve_protein_sequencescommits per UniProt batch for the same reason.
Wire formats and pure decisions behind the GOA universe pass.
Split out of protea.core.operations.ensure_goa_universe when that module
crossed the 800 LOC smell budget. The split is by responsibility, not size: the
operation orchestrates – it queries the database, dispatches HTTP requests and
emits job events – while this module knows only about formats: how UniProt’s
TSV response is laid out, where the audit dates live in its JSON, which evidence
codes each scope admits, and how a returned accession is classified as a merge or
a demerge.
Everything here is pure except _store_dates(), which needs a session
because the three date columns do not fit in UniProtProteinRecord: that model
lives in protea-contracts, so extending it would mean a contract change and
two lock bumps for three dates.
WHAT BROKE AT RELEASE 179, and why the Swiss-Prot rule now demands positive evidence. GOA stopped putting the UniProtKB entry name first in DB Object Synonym and started putting the GENE SYMBOL. Measured 2026-10-06 over the cached releases:
164..178 100% of rows carry an entry name the rule works 179 0% GOA dropped it 180 0% 231 5%
The name is in no other column. The same row reads
A0A021WW32_DROME|vtd|80Fh|... in release 178 and vtd|vtd|80Fh|... in 179,
and A0A021WW32_DROME appears nowhere in it.
The first version of the rule inferred Swiss-Prot from the ABSENCE of the TrEMBL pattern, so with no entry name it returned True for every row: 7.639.329 admissible accessions on release 179 against some 600.000 on each of its predecessors, silently, with the job reporting success. It stalled for three hours in the database phase and was stopped before writing anything. A rule that concludes from an absence fails open, and failing open on the tier that defines the corpus is the worst direction available.
So is_swissprot_entry now requires a name of the shape
<MNEMONIC>_<ORGANISM>, and entry_name_is_readable separates “not reviewed”
from “cannot tell” so the caller can count the second and report it. A release
where the column is unreadable has no swissprot_of_release tier at all, and
that is a warning on the job rather than a suspiciously low admission count.
- protea.core.operations._universe_sources.ACCESSION_GRAMMAR = re.compile('^(?:[OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9](?:[A-Z][A-Z0-9]{2}[0-9]){1,2})$')#
UniProtKB accession grammar, from UniProt’s own documentation.
Two operations need it, for two reasons.
extract_goa_universeuses it as an admission gate, because GOA’s object column is not guaranteed to hold only UniProtKB accessions and an identifier that is not one is not a protein of this universe.resolve_protein_sequencesuses it as a barrier before a batch:/uniprotkb/accessionsanswers 400 for the WHOLE request when one member is malformed, so one stray identifier would cost a thousand proteins.
- protea.core.operations._universe_sources.ALL_KNOWN_CODES = frozenset({'EXP', 'HDA', 'HEP', 'HGI', 'HMP', 'HTP', 'IBA', 'IBD', 'IC', 'IDA', 'IEA', 'IEP', 'IGC', 'IGI', 'IKR', 'IMP', 'IPI', 'IRD', 'ISA', 'ISM', 'ISO', 'ISS', 'NAS', 'ND', 'RCA', 'TAS'})#
asserting the partition.
- Type:
Kept for the one thing it is still good for
- protea.core.operations._universe_sources.AUTOMATIC_CODES = frozenset({'IEA'})#
Excluded, each for its own reason, and the reasons are not interchangeable.
IEAis GO’s only automatic code: no person involved.IBAandIBDcome from the PAINT phylogenetic pipeline, where a curator annotates an ancestral (or descendant) node and the annotation propagates mechanically. There IS a person, but not one looking at this protein, and the label is by construction its family’s consensus. Measured: 58% of the corpus entered byIBAalone when the criterion was “not IEA”, and its share of curated annotation rose from 52% on GOA 156 to 83% on GOA 231.NDrecords that a curator looked and found NOTHING. Its rows sit on the three ontology ROOT terms, whose Information Accretion is zero by construction – IA(v) = -log2 P(v | parents(v)) and P = 1 for a root. So an ND-only donor contributes nothing to an IA-weighted metric AND occupies a slot among the k neighbours: not inert, harmful. Measured on GOA 156: 83,950 accessions carry onlyND, and 83,949 of them have every non-IEA row on a root term.
- protea.core.operations._universe_sources.CURATED_INFERENCE_CODES = frozenset({'IGC', 'IKR', 'IRD', 'ISA', 'ISM', 'ISO', 'ISS', 'NAS', 'RCA'})#
T3, curated inference. A curator judged THIS protein’s function, from sequence similarity, orthology, a sequence model, genomic context or a reviewed computational analysis. Never truth – none of them is a measurement – but a real judgement about a specific protein, unlike T1’s exclusions.
They are in because they are the direct, independent probe of the question the campaign asks:
ISSand friends are curator-reviewed ALIGNMENT inferences, so comparing a nearest-neighbour prediction against them tests whether an embedding neighbourhood captures what curated alignment captures, without touching the scored truth. Measured on GOA 156: 62,363 proteins enter by these and by nothing else.
- exception protea.core.operations._universe_sources.SwissProtTierNotDerivableError#
Bases:
RuntimeErrorThe payload asked for a tier whose data this release does not carry.
Raised AFTER the scan and BEFORE anything is written, which is the only place it can both know the answer and still prevent the damage.
A warning was tried first and was not enough. On release 179 the operation emitted
swissprot_tier_unavailablesaying 98,4% of rows were unreadable, and then went on to insert 1.601.408 proteins admitted by the tier it had just reported as unavailable. A guard that reports and proceeds is a guard that proceeds.
- protea.core.operations._universe_sources.TIER_TRUTH = 'truth'#
The tiers a payload may ask for, by name.
- protea.core.operations._universe_sources.TRUTH_CODES = frozenset({'EXP', 'HDA', 'HEP', 'HGI', 'HMP', 'HTP', 'IC', 'IDA', 'IEP', 'IGI', 'IMP', 'IPI', 'TAS'})#
13 + 9 + 4 = 26, which is every code the ECO mapping knows. Nothing unclassified, nothing invented. An unknown code is therefore a new GO code, and it is REJECTED and counted rather than admitted, because the previous criterion was a complement – “anything that is not IEA” – and a complement admits whatever GO invents next without anybody deciding.
The principle that orders them: a protein is admitted on evidence that is a MEASUREMENT ON THAT PROTEIN, or on a curated database saying it reviewed the entry. Everything excluded fails both.
T1, the truth. The thirteen LAFA scores on: the eleven GO experimental codes plus
ICandTAS. These are the only codes that make a protein an evaluation TARGET, and the set is identical toprotea.core.ia_regimes.LAFA_EVIDENCE– admission criterion and truth criterion are the same set, deliberately.- Type:
THE FOUR TIERS, and the partition is exact
- protea.core.operations._universe_sources.assert_the_tier_is_derivable(counters: _RowCounters, *, admit: Sequence[str]) None#
Refuse a pass that admitted on
swissprot_of_releasewithout the data.The threshold is half the rows. Not a tuned number: a release either carries the entry name in essentially every row or in essentially none. Measured over the cached series, 164..178 carry it in 100% and 179, 180 and 231 in 0%, 0% and 5%. There is no middle to calibrate against.
- protea.core.operations._universe_sources.candidates_from(payload: dict[str, Any], requested: set[str]) tuple[dict[str, list[tuple[str, list[UniProtProteinRecord]]]], dict[str, dict[str, Any]]]#
Group a
sec_acc:search response by the accession that was requested.Everything is collected before anything is decided, because an accession may appear under several entries and is then a demerge rather than a merge. Deciding inside the loop would alias it to whichever entry came first, which is the order of UniProt’s response and not a decision.
- Returns:
(candidates, entry_by_accession). The second mapping is how_audit_dates_of()reachesentryAuditfor rows produced on this path; without it those proteins would carry NULL temporal columns.
- protea.core.operations._universe_sources.classify(candidates: dict[str, list[tuple[str, list[UniProtProteinRecord]]]], alias: dict[str, str], demerges: dict[str, list[str]]) list[UniProtProteinRecord]#
Separate merges from demerges and return the rows to persist.
A demerge has no single identity. An accession returned against more than one primary was split across entries, so there is no one protein it points at: aliasing it to either picks arbitrarily, and the sequence it would inherit belongs to one of two distinct proteins. Such accessions are recorded with their destinations and left unresolved, because choosing is a curatorial decision this operation cannot make.
Rows are deduplicated by accession. One primary can appear under several requested secondaries in the same batch.
InsertProteinsOperation._store_recordssplits inserts from updates by querying existing rows and does not deduplicate its own input – its usual caller receives each accession once from a FASTA stream – so a repeated accession reaches it as two INSERTs and raisesduplicate key. Observed withC8VQ65on 2026-10-05, after 317 correct merges.aliasanddemergesare mutated in place; the return value is the row list for the caller to persist.
- protea.core.operations._universe_sources.codes_for_tiers(tiers: Sequence[str]) frozenset[str]#
Which evidence codes the requested tiers admit.
- Raises:
ValueError – on an unknown tier name, rather than silently dropping it. A scope that quietly widened the corpus is how the original
reviewed:truedefect went unnoticed for a whole campaign, and a tier that quietly NARROWED it would be the same mistake mirrored.
- protea.core.operations._universe_sources.entry_name_is_readable(synonym_field: str) bool#
Whether this row can answer the Swiss-Prot question at all.
Separate from
is_swissprot_entry()because “not reviewed” and “cannot tell” are different facts and the second one has to be counted. GOA dropped the entry name at release 179, so for 52 of the 75 releases of this series every row answers “cannot tell”, and without this the tier would just look like it admitted nobody.
- protea.core.operations._universe_sources.extraction_report(*, release: int, admit: list[str], dry_run: bool, scan: _ScanOutcome, elapsed: float) dict[str, Any]#
The result of one GAF pass, which is its only record.
Here and not in the operation because it is a pure function of its inputs, which is what this module holds.
malformed_accessionsandrows_not_a_proteinare two figures and used to be one: see_RowCounters.
- protea.core.operations._universe_sources.is_swissprot_entry(accession: str, synonym_field: str) bool#
Was this entry reviewed AT THE RELEASE this GAF row comes from?
UniProt names its entries
<mnemonic>_<ORGANISM>in Swiss-Prot and<accession>_<ORGANISM>in TrEMBL. The GAF carries that name in the DB Object Synonym column, as the first|-separated element – and it carries the name OF ITS OWN RELEASE. So the contemporaneous reviewed status is already in the file being read: no historical download, no pairing of a GOA release to a UniProt release, and the date is the GAF’s own rather than the nearest archived release’s.That matters because the alternative is expensive and the shortcut does not work. UniProt’s archive publishes no standalone Swiss-Prot FASTA: only
uniprot_sprot-only<release>.tar.gzat ~1.5 GB, of which 541 MB must be streamed to reach the FASTA member, so ~40 GB for the series. Anddate_createdcannot substitute: it is the UniProtKB integration date, not the Swiss-Prot promotion date, so an entry that sat in TrEMBL from 2014 and was reviewed in 2024 carries 2014.MEASURED on GOA 156 against the archived Swiss-Prot of 2016_07:
527,149 accessions classified Swiss-Prot, and the intersection with the archived set is 527,149 – zero false positives, precision 100.000%.
The 24,556 archived entries this does not see are absent from the GAF altogether: 0 of a 20-accession sample appear anywhere in the file. They carry no GO annotation in that release, so they have nothing to donate and cannot be a target. Not seeing them is correct, not a gap.
Every data row carried an entry name: 0 of 280,916,291 were empty.
WHERE THIS RULE STOPS WORKING, and it is not an edge case: GOA dropped the entry name at release 179 and the tier is unavailable from there to the end of the series. The measurement and the row that proves it are in this module’s own docstring, under WHAT BROKE AT RELEASE 179.
So this now requires POSITIVE evidence. A UniProtKB entry name is
<MNEMONIC>_<ORGANISM>: it always contains an underscore and the part after the last one is an uppercase organism code. A first element that does not have that shape is not an entry name, so the question CANNOT BE ANSWERED from this row, and the answer isFalse– the row is left to be decided by its evidence code alone.Use
entry_name_is_readable()to tell “not Swiss-Prot” from “cannot tell”, because the caller has to count the second case and report it: a release where the column is unreadable has noswissprot_of_releasetier at all, and that has to be visible in the run rather than inferred from a suspiciously round admission count.
- protea.core.operations._universe_sources.records_for_merge(entry: dict[str, Any], requested: set[str]) tuple[str, list[UniProtProteinRecord], list[str]] | None#
The rows one UniProt entry contributes: its primary plus requested aliases.
Aliases are created only for secondary accessions somebody actually asked for. An entry can list dozens –
P04439carries 135 – and materialising the rest would invent proteins no GAF ever annotated.- Returns:
(primary, rows, matched_secondaries), orNonewhen the entry has no sequence or none of its secondaries were requested.
- protea.core.operations._universe_sources.resolution_report(*, dry_run: bool, outcome: _FetchOutcome, elapsed: float) dict[str, Any]#
The result of the pass against UniProt.
Nonein a dry run rather than0, because “zero recoverable” and “not attempted” are not the same thing: an earlier report read 0% recoverable merges because ten batches had answered 400 and the failures were tallied as zeroes.dates_pendingbroke that rule and read0in a dry run while 644.659 rows were waiting, because the pass that counts them is the one a dry run skips. A dry run is exactly where somebody decides whether the real one is worth starting, so the one field that said “nothing to do” was the one that could not know.
Counters and the result record of a GOA annotation load.
Out of load_goa_annotations.py because that file already holds a 500-line
operation and did not need to also hold its bookkeeping. It is the same split
_universe_sources makes for the extraction side, and everything here is a
pure function of its inputs or a plain accumulator, so it is testable without a
session, a GAF or a network.
WHY THE SKIP COUNT IS THREE NUMBERS AND NOT ONE. skipped mixed one expected
rejection with two that are information loss, and the expected one is a thousand
times larger: of GOA 156’s 280.9 million rows, some 270 million belong to proteins
that are not in this corpus at all. A loss of 50,000 rows of OUR OWN superset
inside that is invisible. It is the same defect malformed_skipped had on the
extraction side (ADR-D49), at the other end of the pipeline.
- protea.core.operations._goa_load_report.load_report(*, annotation_set_id: UUID, totals: _GoaPageTotals, ontology_check: Any, elapsed: float) dict[str, Any]#
The job’s result dict, which is the only record of what the pass did.
Here and not in the operation because it is a pure function of its inputs, exactly like
extraction_reporton the other side of the pipeline.
One place that asks whether a window may inform a decision.
Two operations can touch the holdout and they touch it differently:
generate_evaluation_set DEFINES a window, and run_cafa_evaluation
produces a NUMBER against one. Both have to ask, because a window defined
before this guard existed can still be scored today, and the leak happens when
the number is produced rather than when the window is named.
They ask through here rather than each resolving the date itself, so there is
one answer to “which end of the window is compared against the mark” instead of
two that can drift. The rule itself lives in
protea.core.split_registry.assert_window_may_inform(); this only knows how
to find the date it needs in the database.
- class protea.core.operations._holdout_guard.Claim(waiver: str | None = None, declaration: str | None = None)#
Bases:
NamedTupleWhat a caller says about a window that reads past the board’s mark.
The two sentences travel as one object because they are mutually exclusive and nothing else would say so.
HOLDOUT_WAIVERmeans “this is the single pass on the held-back band”;PROSPECTIVE_DECLARATIONmeans “this band begins after that one and selects nothing”. A caller passing both is claiming two different things about one window, and the guard checks the waiver first, so the declaration would be silently ignored and a straddle would pass under a sentence that was never checked.- declaration: str | None#
Alias for field number 1
- waiver: str | None#
Alias for field number 0
- protea.core.operations._holdout_guard.refuse_if_it_reads_the_holdout(session: Session, new_annotation_set_id: UUID, *, claim: Claim, context: str, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None] | None = None, old_annotation_set_id: UUID | None = None) None#
Raise unless the window ending at this corpus may inform a decision.
A corpus with no recorded publication date is passed rather than refused, because the date is what the rule compares and refusing every window on a set that predates the date column would take down the tune windows to protect the holdout from a case that cannot be evaluated either way.
But it is passed LOUDLY: see the sibling function. The absence is not narrow during a rebuild, when no set has a date yet, and a guard that passes in silence for lack of an input is indistinguishable from a guard that approved.
- protea.core.operations._holdout_guard.refuse_if_the_set_reads_the_holdout(new_set: AnnotationSet | None, *, claim: Claim, context: str, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None] | None = None, old_set: AnnotationSet | None = None) None#
The rule, for a caller that already holds the corpus it is ending at.
Separate from the id form so a caller does not pay a second lookup for a row it has already resolved. That is not only cost: an extra query inside an operation is an extra thing a test double has to expect, and the first version of this guard broke three existing tests by asking the session for a row the operation had in hand.
The payload of run_cafa_evaluation, and nothing else.
Out of run_cafa_evaluation.py because that file reached its 800-line budget
and the payload is 254 of them: twenty-six fields, each with the prose that says
what it decides. The budget exists to force exactly this split, and the holdout
guard that pushed the file over it is not the change that should also carry a
refactor.
Re-exported from run_cafa_evaluation so every existing import keeps working.
- class protea.core.operations._run_cafa_payload.RunCafaEvaluationPayload(*, evaluation_set_id: str, holdout_waiver: str | None = None, prospective_declaration: str | None = None, prediction_set_id: str, max_distance: Annotated[float | None, Ge(ge=0.0), Le(le=2.0)] = None, max_k_position: Annotated[int | None, Ge(ge=1)] = None, max_sequence_rank: Annotated[int | None, Ge(ge=1)] = None, scoring_config_id: str | None = None, reranker_id_nk: str | None = None, reranker_id_lk: str | None = None, reranker_id_pk: str | None = None, rerankers: dict[str, dict[str, str]] | None = None, ia_file: str | None = None, information_accretion_set_id: str | None = None, restrict_gt_to_predicted: bool = True, softprop: bool = False, interpro_graft: bool = False, interpro_protein2ipr_file: str | None = None, interpro_ipr2go_file: str | None = None, interpro_graft_weight: Annotated[float | None, Ge(ge=0.0), Le(le=1.0)] = None, th_step: Annotated[float, Gt(gt=0.0), Le(le=1.0)] = 0.01, score_reading: str = 'raw', max_terms: Annotated[int | None, Ge(ge=1)] = None, band: str | None = None, toi_file: str | None = None, toi_rule: str = 'pivot_terms', frame: str | None = None, temporal_window: str | None = None, leakage_role: str | None = None, arms_enabled: dict[str, bool] | None = None, window_role: str | None = None)#
Bases:
ProteaPayloadThe evaluation request. See
max_sequence_rankon counting depth.- arms_enabled: dict[str, bool] | None#
- band: str | None#
- evaluation_set_id: str#
- frame: str | None#
- holdout_waiver: str | None#
Permits the single pass on the holdout; see split_registry.HOLDOUT_WAIVER.
- ia_file: str | None#
- information_accretion_set_id: str | None#
- interpro_graft: bool#
- interpro_graft_weight: float | None#
- interpro_ipr2go_file: str | None#
- interpro_protein2ipr_file: str | None#
- leakage_role: str | None#
- max_distance: float | None#
- max_k_position: int | None#
- max_sequence_rank: int | None#
- max_terms: int | None#
- model_config = {'extra': 'forbid', 'frozen': True, 'strict': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod must_be_non_empty(v: str) str#
- prediction_set_id: str#
- prospective_declaration: str | None#
Permits a band BEYOND the spent holdout, which begins at or after it and so cannot be a second look at it. Refused by name for a window that straddles the band. See split_registry.PROSPECTIVE_DECLARATION.
- reranker_id_lk: str | None#
- reranker_id_nk: str | None#
- reranker_id_pk: str | None#
- rerankers: dict[str, dict[str, str]] | None#
- restrict_gt_to_predicted: bool#
- score_reading: str#
- scoring_config_id: str | None#
- softprop: bool#
- temporal_window: str | None#
- th_step: float#
- toi_file: str | None#
- toi_rule: str#
- window_role: str | None#
Pure helpers extracted from LoadOntologySnapshotOperation.execute.
The OBO load path branches into a fresh-snapshot insert and an
already-exists-but-needs-backfill case; both paths build
GOTermRelationship rows via the same loop. This module hosts the
shared relationship builder plus the two branch handlers, so the
operation file (load_ontology_snapshot.py) can keep execute
under the master plan v3.2 §3 method-LOC ceiling.
- protea.core.operations._load_ontology_helpers.build_relationships(terms: list[dict[str, Any]], go_id_to_db_id: dict[str, UUID], snapshot_id: UUID) list[GOTermRelationship]#
Materialise GOTermRelationship rows for the given parsed terms.
termscarry their parent edges in("relation_type", "GO:nnn")tuples under therelationshipskey (parser output). Edges pointing at GO ids absent fromgo_id_to_db_idare silently skipped so a partial snapshot does not abort the whole insert.
- protea.core.operations._load_ontology_helpers.handle_existing_snapshot(session: Session, existing: OntologySnapshot, terms: list[dict[str, Any]], obo_version: str, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
Resolve an idempotent re-run of
load_ontology_snapshot.Returns the existing snapshot id as a no-op when its relationship rows are already present; otherwise dispatches to
_backfill_relationships()(the GO terms themselves are assumed present from the original load).
- protea.core.operations._load_ontology_helpers.insert_new_snapshot(session: Session, obo_url: str, obo_version: str, terms: list[dict[str, Any]], started_at: float, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult#
Create the snapshot, terms, and relationship rows in a single flow.
The caller has already validated the payload, downloaded the OBO, and parsed the terms; this function commits the three inserts and emits the
doneaudit event with the elapsed runtime.
Wire from PROTEA’s predict_go_terms_batch operation to
protea_method.pipeline.predict.
The orchestrator (PredictGOTermsBatchOperation.execute) used to
duplicate the KNN + vote-accumulation logic inline (both the
unified-pool and the aspect-separated paths), then layer PROTEA-only
metadata on top of each prediction record. F2C.5a routed the
unified-pool path through protea_method.pipeline.predict; F2C.5b
adds the aspect-separated wire and drops the legacy receipt code now
that protea-method 0.3.0 stamps every PROTEA field the orchestrator
needs.
What this adapter still owns#
KNN pre-search to identify unique neighbours (so PROTEA can load alignment / taxonomy / annotation inputs for only the refs that actually voted on a query). Cheap relative to the DB joins it avoids.
pipeline.predict()re-runs the KNN internally; the cached numpy arrays make that a no-op even at production sizes.Building the per-(query, donor_ref)
pair_featuresdict the v6 enricher consumes downstream, and whichpipeline.predict()propagates onto each emitted row.
What pipeline.predict() now owns (delegated)#
Vote tally, donor-ref selection, vote_count / k_position /
go_term_frequency / ref_annotation_density /
neighbor_distance_std / neighbor_vote_fraction /
neighbor_min_distance / neighbor_mean_distance, legacy
min_distance / mean_distance / distance, aspect,
qualifier / evidence_code, prediction_set_id,
ref_protein_accession, pair-feature propagation.
The reranker (booster) stays out of this call. PROTEA still
applies it via _apply_reranker_if_aligned AFTER ancestor
expansion, which keeps the historical ordering bit-exact.
Smell budget: kept under file 800 / class 500 / method 60 ceilings.
- class protea.core.operations._predict_go_terms_adapter.AdapterInputs(p: PredictGOTermsBatchPayload, valid_accessions: list[str], query_embeddings: np.ndarray, ref_data: dict[str, Any], annotations: dict[str, list[dict[str, Any]]], go_id_map: dict[int, str], go_aspect_map: dict[int, str], prediction_set_id: uuid.UUID, ref_sequences: dict[str, str], query_sequences: dict[str, str], ref_tax_ids: dict[str, int | None], query_tax_ids: dict[str, int | None], alignment_cache: Any = None, ref_sequence_identities: dict[str, str] | None = None)
Bases:
NamedTupleBundle of data inputs the adapter consumes.
Keeps the public adapter functions under flake8-bugbear’s parameter ceiling.
ref_datacarries the unified reference pool the orchestrator already cached (embeddings_f32/embeddings_f32_cos/accessions); the adapter picks the cosine-normalised view when the payload’s metric is"cosine".- alignment_cache: Any
Alias for field number 12
- annotations: dict[str, list[dict[str, Any]]]
Alias for field number 4
- go_aspect_map: dict[int, str]
Alias for field number 6
- go_id_map: dict[int, str]
Alias for field number 5
- p: PredictGOTermsBatchPayload
Alias for field number 0
- prediction_set_id: uuid.UUID
Alias for field number 7
- query_embeddings: np.ndarray
Alias for field number 2
- query_sequences: dict[str, str]
Alias for field number 9
- query_tax_ids: dict[str, int | None]
Alias for field number 11
- ref_data: dict[str, Any]
Alias for field number 3
- ref_sequence_identities: dict[str, str] | None
Alias for field number 13
- ref_sequences: dict[str, str]
Alias for field number 8
- ref_tax_ids: dict[str, int | None]
Alias for field number 10
- valid_accessions: list[str]
Alias for field number 1
- class protea.core.operations._predict_go_terms_adapter.AdapterResult(predictions: list[dict[str, Any]], pair_features: dict[tuple[str, str], dict[str, Any]], neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]], go_map_by_aspect: dict[str, dict[str, list[dict[str, Any]]]], repaired_pair_features: int = 0)
Bases:
NamedTupleOutput bundle: enriched predictions +
pair_featuresfor v6.pair_featuresis keyed by(q_acc, ref_acc)and carries the alignment / taxonomy columns the v6 enricher (KnnEnrichmentContext) expects.neighbors_by_aspectandgo_map_by_aspectare re-exported from the diagnostics so the v6 shim can reuse them without re-running KNN.- go_map_by_aspect: dict[str, dict[str, list[dict[str, Any]]]]
Alias for field number 3
- neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]]
Alias for field number 2
- pair_features: dict[tuple[str, str], dict[str, Any]]
Alias for field number 1
- predictions: list[dict[str, Any]]
Alias for field number 0
- repaired_pair_features: int
How many
(query, donor)pairs the pre-search did not anticipate and this call had to compute after the fact. Expected to be 0. A non-zero value is not damage, the rows are repaired before they are returned, but it says the two searches disagreed and by how much.
- protea.core.operations._predict_go_terms_adapter.call_pipeline_predict(inputs: AdapterInputs) AdapterResult
Run
protea_method.pipeline.predictfor the unified-pool path.Returns the prediction dicts shaped exactly as PROTEA’s downstream consumers expect (
protea-method0.3.0 stamps every PROTEA field, includingprediction_set_idviaPredictConfig), plus the pair-feature dict the v6 enricher wants and the diagnostics’ aspect maps for the v6 context.
- protea.core.operations._predict_go_terms_adapter.call_pipeline_predict_aspect_separated(inputs: AdapterInputs, neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]]) AdapterResult
Run
pipeline.predict(aspect_separated=True)for the per-aspect path.The caller has already KNN-searched each aspect’s pre-filtered reference pool and loaded the union of hit-ref annotations (across aspects).
protea-methodre-runs the partitioned KNN against the unified pool we pass. Both put a ref in aspecta’s bank iff at least one of its annotations resolves to aspecta, so the two searches see the same members.THEY DO NOT PRODUCE THE SAME NUMBERS. This docstring used to say the two were bit-exact; it is measurably not, and
_repair_pair_featuresbelow carries the measurement and repairs what the disagreement drops.The redundant KNN inside
pipeline.predict()keeps the delegation pure (no neighbour injection): the numpy arrays are warm in L3 by then, so the cost is dwarfed by the annotation and sequence loads the pre-search saved. Believing it was also exact is what made this class of defect invisible.
Aspect-separated KNN pre-search + adapter input builder.
Extracted from the monolithic predict_go_terms.py as part of T2B.6.
Behaviour is unchanged.
- protea.core.operations.predict_go_terms._aspect_helpers.call_pipeline_predict_aspect_separated(inputs: AdapterInputs, neighbors_by_aspect: dict[str, list[list[tuple[str, float]]]]) AdapterResult
Run
pipeline.predict(aspect_separated=True)for the per-aspect path.The caller has already KNN-searched each aspect’s pre-filtered reference pool and loaded the union of hit-ref annotations (across aspects).
protea-methodre-runs the partitioned KNN against the unified pool we pass. Both put a ref in aspecta’s bank iff at least one of its annotations resolves to aspecta, so the two searches see the same members.THEY DO NOT PRODUCE THE SAME NUMBERS. This docstring used to say the two were bit-exact; it is measurably not, and
_repair_pair_featuresbelow carries the measurement and repairs what the disagreement drops.The redundant KNN inside
pipeline.predict()keeps the delegation pure (no neighbour injection): the numpy arrays are warm in L3 by then, so the cost is dwarfed by the annotation and sequence loads the pre-search saved. Believing it was also exact is what made this class of defect invisible.
- protea.core.operations.predict_go_terms._aspect_helpers.run_aspect_separated_knn(op: PredictGOTermsBatchOperation, session: Session, ctx: AspectSeparatedKnnContext) tuple[list[dict[str, Any]], dict[str, list[list[tuple[str, float]]]], dict[str, dict[str, list[dict[str, Any]]]], dict[tuple[str, str], dict[str, Any]]]
Delegate aspect-separated KNN + vote tally to
pipeline.predict(aspect_separated=True). Returns the legacy 4-tuple shape v6 / ancestor / reranker consumers still expect. See F2C.5b notes.
- protea.core.operations.predict_go_terms._aspect_helpers.run_aspect_separated_path(op: PredictGOTermsBatchOperation, session: Session, ctx: Any, query_batch: Any, ref_data: Any) Any
Aspect-separated KNN dispatch; one pass per GO aspect.
Returns
_KnnResultshaped output (imported lazily to avoid a circular import with_batch_op).
PredictGOTermsBatchOperation and its execute-time helper context types.
Extracted from the monolithic predict_go_terms.py as part of T2B.6.
T2B.4 then lifted the reranker scoring path out of the
_RerankerMixin hierarchy into the compositive
protea.core.operations.predict_go_terms._reranker_scorer.RerankerScorer,
so the orchestrator now collaborates with the scorer through a
constructor-injected instance instead of through MRO.
F2C.5c (the orchestrator collapse) moves the unified-pool, aspect-
separated, post-KNN, and chunked-publish bulk-logic helpers out into
sibling modules (_unified_path, _aspect_helpers,
_post_knn_pipeline, _store). The orchestrator keeps
short delegate methods so existing unit tests that patch.object on
PredictGOTermsBatchOperation keep working without churn, while
the class itself drops well below the master plan §3 500-LOC ceiling.
- class protea.core.operations.predict_go_terms._batch_op.PredictGOTermsBatchOperation(reranker_scorer: RerankerScorer | None = None)
Bases:
_ReferenceMixin,_FeatureLoadingMixinCPU batch worker: KNN search + GO annotation transfer for one query chunk.
Reference embeddings and their GO annotations are loaded from DB on first access and cached at the process level (_REF_CACHE). Subsequent batch messages reuse the cached reference without any DB round-trip.
Result is published to
protea.predictions.writefor bulk DB insertion. The reranker scoring path is delegated to an injectedRerankerScorercollaborator (T2B.4). The unified-pool, aspect-separated, post-KNN and chunked-publish helpers live in sibling modules (F2C.5c orchestrator collapse).- description = 'CPU child job: KNN search and GO annotation transfer for one query chunk; result is forwarded to store_predictions.'
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult
- name = 'predict_go_terms_batch'
- summarize_payload(payload: dict[str, Any]) str
- protea.core.operations.predict_go_terms._batch_op.call_pipeline_predict(inputs: AdapterInputs) AdapterResult
Run
protea_method.pipeline.predictfor the unified-pool path.Returns the prediction dicts shaped exactly as PROTEA’s downstream consumers expect (
protea-method0.3.0 stamps every PROTEA field, includingprediction_set_idviaPredictConfig), plus the pair-feature dict the v6 enricher wants and the diagnostics’ aspect maps for the v6 context.
- protea.core.operations.predict_go_terms._batch_op.enrich_v6_features(predictions: list[dict[str, Any]], *, session: Session, ctx: KnnEnrichmentContext, compute_taxonomy: bool) None
Compute the 25 v6 features and merge them into each
preddict in place.PROTEA-side wrapper around
protea_method.feature_enricher.enrich_v6_features: collects the GO term ids in play, loads the metadata maps from the database, and forwards everything to the library function. The library does the Anc2Vec pool, neighbor centroids, tax voters, PCA projection, and per-row merge.
Feature / annotation / embedding loading mixin for the batch op.
Pulled out of the monolithic predict_go_terms.py as part of T2B.6.
Holds the methods that materialise per-batch query embeddings, the
non-negated annotation map, sequences / taxonomy fields for the
optional feature families, and the GO term metadata map consumed by the
adapter.
Reference-pool loading mixin for PredictGOTermsBatchOperation.
Holds every method that materialises and slices the per-aspect / unified
reference embedding caches. Pulled out of the monolithic
predict_go_terms.py as part of T2B.6 so the file budget stays under
the §3 ceiling.
Backward-compat shim for the legacy _RerankerMixin import path.
The reranker scoring path was extracted into the compositive
protea.core.operations.predict_go_terms._reranker_scorer.RerankerScorer
class as part of T2B.4. This module retains the top-level symbol
exports (load_reranker, apply_reranker, load_settings,
get_artifact_store, infer_active_feature_families) so existing
tests that patch this module path continue to work transparently
without rewriting their mocks. New code should construct
RerankerScorer directly.
- protea.core.operations.predict_go_terms._batch_op_reranker.apply_reranker(df: pandas.DataFrame, booster: lightgbm.Booster, *, feature_cols: list[str] | None = None) numpy.ndarray
Score
dfwithboosterand return an aligned array.If
feature_colsis None we use the booster’s ownfeature_name(). Missing columns are filled withnp.nanso LightGBM routes them through its native missing-value branch rather than crashing on KeyError.
- protea.core.operations.predict_go_terms._batch_op_reranker.get_artifact_store(settings: Settings)
- protea.core.operations.predict_go_terms._batch_op_reranker.infer_active_feature_families(*, compute_alignments: bool, compute_taxonomy: bool, compute_v6_features: bool, compute_lineage_features: bool = False) list[str]
Map predict-time feature flags onto lab feature families.
Thin PROTEA-side extension of
protea_method.reranker.infer_active_feature_families(): it delegates to the library helper for the base families (knn/annotation_meta/alignment_nw/length/taxonomy_pair/ the v6 bundle) and layers the GO-DAGlineagefamily on top whencompute_lineage_featuresis set.The lineage family is governed here (not in the library) because it is opt-in at serve time via the
compute_lineage_featurespayload flag and must round-trip throughprotea_contracts.compute_feature_schema_sha()so a booster trained with lineage gets a matching live schema sha.Invariant (load-bearing for the FARM-EXP.5 schema-sha guard): with
compute_lineage_features=False(the default) the returned family list is byte-identical to the library output for every align/tax/v6 combination, so the eight existing schema shas (registered trio7fcecf26aa0aetc.) are unchanged. Setting the flag appends exactly thelineagefamily, yielding a new sha (e.g. align+tax+no-v6+lineage ->0810bef8fd4d).
- protea.core.operations.predict_go_terms._batch_op_reranker.load_reranker(artifact_uri: str, *, feature_schema_sha: str, store: ArtifactStore, cache_dir: Path | None = None) lightgbm.Booster
Fetch (once) and load a LightGBM booster by URI.
The first call materialises the booster blob under
cache_dir/<feature_schema_sha>_<uri_tag>.txt; subsequent calls reuse the on-disk file and an in-process booster cache keyed by the URI.storeis used only when the cached file does not exist;artifact_uriis expected to resolve to a store key but the store implementation chooses whether to parse it (LocalFsArtifactStoreignores the URI and resolves keys from its root; MinIO derives the key from thes3://bucket/keyURI).The on-disk cache is namespaced by
feature_schema_shabecause each sha represents a stable column layout; multiple boosters that share a sha need to disambiguate by URI to avoid the in-process cache returning the first-loaded booster for every cell.
- protea.core.operations.predict_go_terms._batch_op_reranker.load_settings(project_root: Path, *, env_prefix: str = 'PROTEA_') Settings
Resolve runtime settings via env >
.env>system.yaml> defaults.See the module docstring for the full env-var contract and the deprecation matrix.
env_prefixdefaults to"PROTEA_"; passing anything else emits aDeprecationWarning.
- protea.core.operations.predict_go_terms._batch_op_reranker.predict(model: lightgbm.Booster, df: pandas.DataFrame, *, categorical_codes: dict[str, list[str]] | None = None) numpy.ndarray
Score predictions using a trained re-ranker.
Returns an array of scores in [0, 1] where higher = more likely correct. For lambdarank boosters, raw scores are unbounded reals; we apply a sigmoid to calibrate them into the [0, 1] range expected by the downstream CAFA evaluator (which sweeps thresholds from 0 to 1). Binary boosters already emit probabilities, so we leave them alone.
categorical_codesis the per-column ordered string vocabulary the lab used at training time ({column: [val0, val1, ...]}). When provided, each cat column is encoded against this fixed vocabulary so the codes match training; when omitted, falls back topd.factorizeover the inference batch (correct only if the batch happens to contain the same set of values in the same order, usually wrong for small or aspect-filtered batches).
Shared constants, parameter objects, and pure helpers.
Extracted from the monolithic protea/core/operations/predict_go_terms.py
as part of T2B.6. No behaviour change; only module location.
- class protea.core.operations.predict_go_terms._common.AspectSeparatedKnnContext(valid_accessions: list[str], query_embeddings: numpy.ndarray, ref_data_by_aspect: dict[str, dict[str, Any]], annotation_set_id: UUID, prediction_set_id: UUID, payload: PredictGOTermsBatchPayload)
Bases:
objectInputs for
PredictGOTermsBatchOperation._run_aspect_separated_knn.Same family as
BatchPredictContextbut for the aspect-separated KNN path: one independent index + neighbor set per GO aspect (P/F/C).ref_data_by_aspectis keyed by aspect char rather than the unifiedref_datadict that_predict_batchconsumes;annotation_set_idis required because aspect-scoped GO annotation lookups happen inside the helper.- annotation_set_id: UUID
- payload: PredictGOTermsBatchPayload
- prediction_set_id: UUID
- query_embeddings: numpy.ndarray
- ref_data_by_aspect: dict[str, dict[str, Any]]
- valid_accessions: list[str]
Coordinator operation that fans out predict_go_terms_batch messages.
Extracted from the monolithic predict_go_terms.py as part of T2B.6.
- class protea.core.operations.predict_go_terms._coordinator.PredictGOTermsOperation
Bases:
objectCoordinator: validates, creates PredictionSet, dispatches N batch messages.
Pipeline:
Validate
EmbeddingConfig,AnnotationSetandOntologySnapshot.Load query accessions that have embeddings (no embedding data; keeps the coordinator session light).
Create the
PredictionSet.Partition accessions into batches and publish to
protea.predictions.batch.
The actual KNN search and GO transfer happen inside
PredictGOTermsBatchOperation.- description = 'Coordinator: create a PredictionSet and partition query proteins into KNN batches dispatched to predict_go_terms_batch workers.'
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult
- name = 'predict_go_terms'
- summarize_payload(payload: dict[str, Any], *, session: Session | None = None) str
Post-KNN pipeline helpers for PredictGOTermsBatchOperation.
F2C.5c extracts the post-KNN dispatch (v6 enrichment, ancestor
expansion, reranker apply) and the synthetic-ancestor FK resolver out
of the orchestrator class so the orchestrator stays under the master
plan §3 class ceiling. Behaviour is unchanged: each helper takes the
PredictGOTermsBatchOperation instance (for DB-bound loader access)
plus an explicit context object, and returns the same shape the inline
method did pre-extraction.
The orchestrator keeps short delegate methods so unit tests that
patch PredictGOTermsBatchOperation._apply_v6_features() and
friends keep working without churn.
- protea.core.operations.predict_go_terms._post_knn_pipeline.apply_association(op: PredictGOTermsBatchOperation, session: Session, annotation_set_id: uuid.UUID, valid_accessions: list[str], prediction_dicts: list[dict[str, Any]], emit: EmitFn) None
Set the cross-aspect
association_*features per candidate.For each query protein with pre-cutoff EXPERIMENTAL known terms
K(p)(from the sameannotation_set_idthe KNN pool uses, never post-cutoff), each candidate termtis scored from the per-set co-occurrence table (build_go_cooccurrence). The actual scoring lives in_score_association_candidates():association_total/association_cross/association_present.Leakage guardrails mirror
apply_self_prior(). If the co-occurrence table is empty for this set every candidate stays at the zero-fill default.
- protea.core.operations.predict_go_terms._post_knn_pipeline.apply_lineage(op: PredictGOTermsBatchOperation, session: Session, ontology_snapshot_id: uuid.UUID, annotation_set_id: uuid.UUID, prediction_dicts: list[dict[str, Any]], emit: EmitFn) None
Fill the four
lineage_*columns per candidate from the GO DAG.For each query protein with pre-cutoff EXPERIMENTAL known terms
K(p)(resolved from the sameannotation_set_idthe KNN pool uses, never a post-cutoff set), each candidate termtgetsis_ancestor_of_known/ancestor_of_count(how many known termstis an ancestor of) andis_descendant_of_known/descendant_of_count(the inverse). Values are byte-identical to the library producer; seeprotea.core._feature_enricher_helpers.compute_lineage_into().Leakage guardrails mirror
apply_association: known terms come from the pre-cutoff set only, NOT-qualified rows are dropped by_load_annotations_for, and non-experimental evidence is filtered out.
- protea.core.operations.predict_go_terms._post_knn_pipeline.apply_self_prior(op: PredictGOTermsBatchOperation, session: Session, annotation_set_id: uuid.UUID, valid_accessions: list[str], prediction_dicts: list[dict[str, Any]], emit: EmitFn) None
Set
self_prior_scorefrom each query’s OWN pre-cutoff annotation.The self-prior re-injects the GOA Non-exp signal the KNN scoring discards (it excludes the neighbour self-hit by accession). For every candidate
(protein, go_term_id)the query already carries among its OWN pre-cutoff NON-experimental annotations,self_prior_scoreis set to1.0; all other candidates keep the zero-fill default.Leakage guardrails (load-bearing): annotations come from the same pre-cutoff
annotation_set_idthe KNN reference pool uses (NEVER a post-cutoff set); NOT-qualified rows are dropped by_FeatureLoadingMixin._load_annotations_for(); experimental evidence codes are filtered out viaprotea.core.evidence_codes.is_experimental()so no experimental self annotation can leak in.
- protea.core.operations.predict_go_terms._post_knn_pipeline.apply_v6_features(op: PredictGOTermsBatchOperation, session: Session, ctx: _BatchExecCtx, knn_result: _KnnResult, ref_data: Any, emit: EmitFn) None
Run Anc2Vec / tax_voters / emb_pca enrichment on the prediction list in place. PCA is fitted (or loaded from cache) over the full unified embedding pool; for aspect-separated mode the per-aspect f32 arrays are concatenated first.
- protea.core.operations.predict_go_terms._post_knn_pipeline.expand_to_ancestors(op: PredictGOTermsBatchOperation, session: Session, p: PredictGOTermsBatchPayload, prediction_dicts: list[dict[str, Any]], emit: EmitFn) list[dict[str, Any]]
Expand each leaf prediction to its ancestor closure.
Mirrors what the offline dump helper emits so live predictions carry the same candidate distribution the booster trained on.
- protea.core.operations.predict_go_terms._post_knn_pipeline.resolve_synthetic_fks(session: Session, prediction_dicts: list[dict[str, Any]], int_to_str: dict[int, str], snapshot_id: UUID) list[dict[str, Any]]
Stamp
go_term_idon synthetic ancestor records via the snapshot.
- protea.core.operations.predict_go_terms._post_knn_pipeline.run_post_knn_pipeline(op: PredictGOTermsBatchOperation, session: Session, ctx: _BatchExecCtx, knn_result: _KnnResult, ref_data: Any, emit: EmitFn) tuple[list[dict[str, Any]], dict[str, Any] | None]
Apply v6 enrichment, ancestor expansion, and the reranker.
Returns
(prediction_dicts, reranker_stats). Ancestor expansion runs AFTER v6 so synthetic ancestor records inherit the leaf’sanc2vec_/emb_pca_values, mirroring what the dump helper emits; without that the lab booster sees a feature distribution it never trained on.
- protea.core.operations.predict_go_terms._post_knn_pipeline.stamp_go_ids(session: Session, prediction_dicts: list[dict[str, Any]]) dict[int, str]
Materialise
go_idstrings on each prediction by FK lookup.Returns the
int -> strmap so the synthetic-ancestor FK resolver can reuse it without re-querying.
Compositive RerankerScorer for PredictGOTermsBatchOperation.
Extracted from the T2B.6 _RerankerMixin as part of T2B.4. The
scoring path now lives in a dedicated class with single responsibility
(load booster, score predictions, emit audit events) and is injected
into the batch operation via the constructor rather than mixed in via
MRO. The mixin module
(protea.core.operations.predict_go_terms._batch_op_reranker)
is retained as a thin re-export shim so tests that patch the legacy
symbol path keep working.
Design notes:
The scorer is stateless; one instance per operation is fine, but a fresh instance per call is also safe.
The four external function dependencies (
load_settings,get_artifact_store,load_reranker,apply_reranker) are resolved at call time via attribute lookup on the shim module (_batch_op_reranker). This preserves the existing test pattern that monkeypatches those symbols on the shim module path.The single cross-module collaborator (the GO-term-aspect attach helper) is injected as a callable, so the scorer never reaches back into the orchestrator.
- protea.core.operations.predict_go_terms._reranker_scorer.AttachCategoryFn
Loader for the per-(protein, aspect) CAFA category, injected so unit tests can stub the DB-bound annotation lookup. Signature mirrors
_category_dispatch.attach_query_category()(op is supplied by the scorer’s owner when wired;Nonefalls back to the module default).alias of
Callable[[Session, uuid.UUID,list[dict[str,Any]]],dict[str,int]]
- class protea.core.operations.predict_go_terms._reranker_scorer.RerankerScorer(*, attach_aspect: Callable[[Session, list[dict[str, Any]]], None], attach_category: Callable[[Session, UUID, list[dict[str, Any]]], dict[str, int]] | None = None)
Bases:
objectLightGBM reranker scoring collaborator.
Encapsulates the live-vs-expected feature-schema reconciliation, the booster load, and the in-place scoring pass over a batch’s prediction dicts. Consumed by
PredictGOTermsBatchOperationvia constructor injection.- apply(session: Session, prediction_dicts: list[dict[str, Any]], p: PredictGOTermsBatchPayload, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) dict[str, Any] | None
Entry point: per-category dispatch when bound, else single booster.
When the payload carries all three per-category bindings the batch is split by each candidate’s CAFA category (computed from the protein’s pre-cutoff experimental annotations) and each subset is scored with the matching booster. Otherwise behaviour is identical to
apply_if_aligned()(no regression; default off).
- apply_if_aligned(session: Session, prediction_dicts: list[dict[str, Any]], p: PredictGOTermsBatchPayload, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) dict[str, Any] | None
Score
prediction_dictswith the configured reranker.The booster is skipped silently (returns
None) only when a precondition makes scoring undefined rather than wrong: the operation was dispatched without artifact context, or theprotea_contractsmodule is not importable in this image.Schema-sha drift, in contrast, is a HARD failure: when the live
compute_feature_schema_sha(...)disagrees with the booster’s recordedfeature_schema_shathe method emits thereranker.schema_mismatchevent at error level, logs to the stdlib logger, and raisesSchemaShaMismatchError. The base worker translates that exception intoJob.status=failedwithJob.error_code='SchemaShaMismatchError'(FARM-EXP.5).On success
reranker_scorelands on every prediction dict in memory (not persisted) and the method returns per-batch summary stats.
- record_blob_provenance(p: PredictGOTermsBatchPayload, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) str
ADR D45 value-skew guard: record blob provenance, warn on mismatch.
Thin delegate to
_blob_provenance.record_blob_provenance(). The four LAFA/IA producer families (classifier, self_prior, association, IA) carry a train/serve VALUE skew risk thatfeature_schema_shacannot see (the “0.3462 incident”), so it passes the schema guard silently. The guard derives provenance from the predict-time payload, so the signal-store code-switch (values now in typed columns, not the JSONB blob) does not change it. This records the live provenance and, on a mismatch against the payload’s recorded expected provenance, warns loudly and PROCEEDS (never raises).
- resolve_live_schema_sha(p: PredictGOTermsBatchPayload, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) str | None
Compute the live feature-schema SHA via
protea_contracts.Returns the SHA on success or
Nonewhen the contracts module is unavailable (the booster is skipped silently in that case so production images without the dev dep can still serve KNN distance ordering).
- score(session: Session, prediction_dicts: list[dict[str, Any]], p: PredictGOTermsBatchPayload) Any
Load the booster, score predictions in-place, return the score array.
Two scoring shapes are supported:
per-cell boosters: scored via
apply_rerankerover the booster’s ownfeature_name()order (the historical path).universal boosters (single, pooled, aspect-conditioned, K-augmented): detected by the presence of both
plm_idandk_contextin the booster’s feature list. These carry injected source constants and a fixed categorical vocabulary the genericapply_rerankercannot reproduce, so they are routed throughprotea.core._universal_reranker.score_universal()with thecategorical_codes+ plm/k metadata recovered from the model’s siblingrun.json(F-RERANK-UNIVERSAL inference wiring).
- exception protea.core.operations.predict_go_terms._reranker_scorer.SchemaShaMismatchError(*, reranker_model_id: str | None, expected_sha: str, live_sha: str)
Bases:
ExceptionA booster’s recorded
feature_schema_shadoes not match the live schema.Raised by
RerankerScorerbefore booster load when the payload’sreranker_feature_schema_sha(the value persisted on theRerankerModelrow at registration time) disagrees with whatprotea_contracts.compute_feature_schema_sha()returns for the currently active feature families.The base worker translates this into
Job.status=FAILEDwithJob.error_code="SchemaShaMismatchError"; the structured machine tokenreason="schema_sha_mismatch"is carried on both the emittedreranker.schema_mismatchevent and thereasonclass attribute so downstream consumers can branch on a stable literal.FARM-EXP.5 guard: silent prediction with a stale booster layout is exactly the failure mode this exception exists to prevent.
- reason: str = 'schema_sha_mismatch'
Canonical machine-readable reason literal. Carried on every instance so callers can getattr(exc, ‘reason’, None) without hardcoding the class name.
Write worker: bulk-insert GOPrediction rows + close parent job.
Extracted from the monolithic predict_go_terms.py as part of T2B.6.
- class protea.core.operations.predict_go_terms._store.StorePredictionsOperation
Bases:
objectWrite worker: bulk-inserts GOPrediction rows and updates parent job progress.
Receives serialized prediction dicts from PredictGOTermsBatchOperation, inserts them into the DB, and atomically increments the parent Job’s progress counter. When the last batch is stored the parent Job is closed as SUCCEEDED.
- description = 'CPU child job: bulk-insert GOPrediction rows from a batch and atomically advance the parent predict_go_terms progress counter.'
- execute(session: Session, payload: dict[str, Any], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) OperationResult
- name = 'store_predictions'
- summarize_payload(payload: dict[str, Any]) str
- protea.core.operations.predict_go_terms._store.chunked_publish(*, parent_job_id: UUID, prediction_set_id: UUID, prediction_dicts: list[dict[str, Any]]) list[tuple[str, dict[str, Any]]]
Split predictions into RabbitMQ-sized chunks for the write queue.
RabbitMQ caps message size at 128 MB; ancestor-expanded batches serialise to ~250-300 MB and silently land in the dead-letter queue. Splitting into ~10k-row chunks (~20-25 MB each) keeps the broker happy and lets the parent job’s batch counter advance only on the final chunk via
is_final_chunk.
Unified-pool KNN dispatch helpers for PredictGOTermsBatchOperation.
F2C.5c extracts the unified-pool wire (KNN pre-search, annotation
load, pair-input load, pipeline.predict call) out of the
orchestrator class so the orchestrator stays under the master plan
§3 class ceiling. Behaviour is unchanged; each helper takes the
orchestrator instance for DB-bound loader access plus an explicit
context object, and returns the same shape the inline method did
pre-extraction.
The orchestrator keeps short delegate methods so unit tests that
patch PredictGOTermsBatchOperation._run_unified_path() and
friends keep working without churn.
- protea.core.operations.predict_go_terms._unified_path.run_unified_path(op: PredictGOTermsBatchOperation, session: Session, ctx: _BatchExecCtx, query_batch: _QueryBatch, ref_data: Any, emit: EmitFn) _KnnResult | None
Unified-pool KNN via
protea_method.pipeline.predict.Returns
Nonewhen the reference pool is empty (caller short-circuits with a no-op result).
- protea.core.operations.predict_go_terms._unified_path.unified_load_annotations(op: PredictGOTermsBatchOperation, session: Session, ctx: _UnifiedPredictContext, sequence_keys: dict[str, str] | None = None) tuple[dict[str, list[dict[str, Any]]], set[str]]
Pre-search KNN to resolve the unique-neighbour set, then load the lazy go-map only for those references.
sequence_keyscovers the queries and the WHOLE bank, read before this runs and reused downstream; None when the run did not ask for it.
- protea.core.operations.predict_go_terms._unified_path.unified_load_pair_inputs(op: PredictGOTermsBatchOperation, session: Session, ctx: _UnifiedPredictContext, unique_neighbors: set[str]) tuple[dict[str, str], dict[str, str], dict[str, int | None], dict[str, int | None]]
Conditionally load sequences (alignments) and taxonomy ids.
- protea.core.operations.predict_go_terms._unified_path.unified_predict_via_pipeline(op: PredictGOTermsBatchOperation, session: Session, ctx: _UnifiedPredictContext) AdapterResult
Run the unified KNN path through
protea_method.pipeline.predict.Resolves the GO term metadata maps, sequences / taxonomy inputs (when the payload requests them), and the lazy
go_mapkeyed on neighbours actually found, then delegates tocall_pipeline_predict(). The adapter returns the legacy prediction shape PROTEA’s downstream consumers expect, plus thepair_featuresand aspect maps the v6 enricher needs.
Artifact-IO helpers extracted from run_cafa_evaluation.
These pure functions handle downloading inputs (OBO, IA TSV), writing
ground-truth / prediction TSVs that cafaeval consumes, and parsing
the metrics it produces. Module-level so the operation file
(run_cafa_evaluation.py) can stay focused on the orchestrator and
shrink toward the master-plan v3.2 §3 LOC ceiling.
- class protea.core.operations._run_cafa_artifacts.WritePredictionsContext(pred_set_id: UUID, delta_proteins: set[str], max_distance: float | None, path: str, max_k_position: int | None = None, max_sequence_rank: int | None = None, bank_annotation_set_id: UUID | None = None, denial_snapshot_id: UUID | None = None)#
Bases:
objectShared inputs for the per-setting prediction TSV writers.
Bundles the query-shaped fields (
pred_set_id,delta_proteins,max_distance,max_k_position) plus the destinationpathconsumed by all three artifact writers (write_predictions,write_predictions_reranked,write_predictions_per_aspect). The session, scoring snapshot, and reranker bundle stay outside ctx because they encode IO / scoring strategy, not query parameters.- bank_annotation_set_id: UUID | None = None#
The annotation set the bank was built from, so a candidate can be checked against what that bank explicitly DENIES about the query. None leaves the check off, which is the behaviour every caller had before.
- delta_proteins: set[str]#
- denial_snapshot_id: UUID | None = None#
if a protein does not have the parent, it does not have any descendant, which is the contrapositive of the usual upward propagation of a positive.
- Type:
The ontology the denial is propagated under. A NOT propagates DOWN
- max_distance: float | None#
- max_k_position: int | None = None#
- max_sequence_rank: int | None = None#
The same depth counted in distinct sequences. Exactly one of the two is set;
_depth_unit_guardrefuses a run that names both or that names this one against candidates that cannot answer in it.
- path: str#
- pred_set_id: UUID#
- protea.core.operations._run_cafa_artifacts.attach_term_ia(df: Any, ia_map: dict[str, float]) None#
Inject a normalised
term_iacolumn (in-place) keyed bygo_id.Maps each row’s
go_idto its raw IA, then min-max-normalises against the 99th percentile of the positive IA values (clipped to [0, 1]). The p99 anchor (rather than the raw max) keeps the common dynamic range from being squashed by a handful of extreme-IA terms, while preserving the monotone ordering the specificity prior relies on. Terms absent from the IA file getNaNso the scorer leaves them at multiplier 1.0 (no penalty), matching the cafaeval uniform-IC fallback. Always overwrites any pre-existingterm_iacolumn.
- protea.core.operations._run_cafa_artifacts.download_obo(url: str, dest: str) None#
Download OBO file to dest, decompressing gzip if needed.
- protea.core.operations._run_cafa_artifacts.download_tsv(url: str, dest: str) None#
Copy or download a plain-text TSV file (gzip-transparent) to dest.
Accepts HTTP(S) URLs,
s3://bucket/keyartifact-store URIs, and local filesystem paths (absolute orfile://scheme). Local paths are resolved without any network request, which is useful during development when the IA file lives inside the repository (data/benchmarks/IA_cafa6.tsv) andia_urlis set to its absolute path. Once the file is pushed to GitHub the URL can be switched to the raw.githubusercontent.com address and the same code path handles it transparently.s3://is resolved through the configuredArtifactStorerather than over HTTP, which is what makes an artifact published bycompute_information_accretionreadable from any machine that shares the object store. The bucket in the URI must match the configured bucket: a mismatch means the URI was produced against a different deployment, and silently reading the same key out of the local bucket would hand back a different file under the right-looking name.
- protea.core.operations._run_cafa_artifacts.load_ia_map(ia_path: str) dict[str, float]#
Parse a cafaeval IA TSV (
go_id<TAB>raw_ia) into{go_id: raw_ia}.The IA file is the SAME
go_id-keyed information-accretion table the cafaevalf_micro_wmetric weights with, so attaching it as the scorer’sia_priorsource aligns the prior exactly with the objective. Raw IA is unbounded (0 .. ~19);attach_term_ia()normalises it to [0, 1] before the scorer consumes it asterm_ia.
- protea.core.operations._run_cafa_artifacts.parse_results(dfs_best: dict) dict[str, Any]#
Extract per-namespace Fmax metrics from cafaeval dfs_best.
The unweighted metrics are read from
dfs_best["f"](one row per namespace at the threshold optimising the protein-mean Fmax). When an IA file was supplied to cafaeval, the IA-weighted equivalents land indfs_best["f_w"](best by IA-weighted Fmax) and the micro-averaged Fmax indfs_best["f_micro"]/dfs_best["f_micro_w"]; these are surfaced here as the_w/_micro/_micro_wkeys so chapter-6 tables can pull them without re-reading the per-tier TSV artifacts.
- protea.core.operations._run_cafa_artifacts.write_gt(annotations: dict[str, set[str]], path: str) None#
Write {protein: {go_id}} to a 2-column TSV (no header).
- protea.core.operations._run_cafa_artifacts.write_predictions(session: Session, ctx: WritePredictionsContext, *, scoring_config: ScoringConfig | None = None, reranker_bundle: dict[str, Any] | None = None, known_gos: dict[str, set[str]] | None = None) None#
Write CAFA-format predictions (proteintgo_idtscore) for delta proteins.
- Scoring priority:
If
reranker_bundleis provided, apply the LightGBM model to all predictions and use re-ranker probabilities as scores. The bundle is{"model": str, "cat_codes": dict|None, "universal": dict|None}; a non-Noneuniversalblock routes scoring throughscore_universal()(F-RERANK-UNIVERSAL eval wiring).If a
ScoringConfigis provided, compute scores viacompute_score().Otherwise fall back to
1 - cosine_distance / 2.
known_goscarries the query’s pre-cutoff annotations (LK / PK settings); for NK it must stayNone.
- protea.core.operations._run_cafa_artifacts.write_predictions_per_aspect(session: Session, ctx: WritePredictionsContext, *, aspect_models: dict[str, dict[str, Any]], known_gos: dict[str, set[str]] | None = None) None#
Write CAFA-format predictions applying per-aspect LightGBM models.
aspect_modelsmaps GO aspect char (P/F/C) to{"model": str, "cat_codes": dict|None}bundles. Predictions whose aspect has no model fall back to1 - distance/2.known_goscarries the query’s pre-cutoff annotations (LK / PK settings); must beNonefor NK.
- protea.core.operations._run_cafa_artifacts.write_predictions_reranked(session: Session, ctx: WritePredictionsContext, *, reranker_bundle: dict[str, Any], known_gos: dict[str, set[str]] | None = None) None#
Write CAFA-format predictions using LightGBM re-ranker scores.
reranker_bundleis{"model": str, "cat_codes": dict|None, "universal": dict|None}. A non-Noneuniversalblock routes scoring through_score_bundle_df()/protea.core._universal_reranker.score_universal()(the universal booster carries injectedplm_id/k_contextfeature columns the genericreranker_predictcannot encode); the per-cell path is unchanged (F-RERANK-UNIVERSAL eval wiring).
Pre-cafaeval data preparation helpers extracted from
RunCafaEvaluationOperation.execute.
These pure functions operate on the in-memory EvaluationData
buckets before cafaeval is invoked: they restrict the ground truth
to the actually-predicted protein cohort, which is the standard CAFA
practice that prevents delta proteins outside the PredictionSet’s
query coverage from hurting Fmax / coverage.
- protea.core.operations._run_cafa_data_helpers.MIN_GATED_COHORT = 50#
Below this many ground-truth proteins the restriction gate stays silent. The real incidents were over 6,216; anything two orders of magnitude smaller is not an evaluation whose cohort ratio means anything.
- protea.core.operations._run_cafa_data_helpers.restrict_data_to_predicted(session: Session, *, prediction_set_id: UUID, data: EvaluationData, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) EvaluationData#
Drop ground-truth proteins not present in the PredictionSet cohort.
Without this filter, delta proteins that the PredictionSet never actually predicted (e.g. the booster failed for them, or they were excluded at query time) would still count as “missing” against Fmax / coverage. CAFA practice is to evaluate only on the predicted cohort.
Returns a new
EvaluationDatawith each of the five{protein → set[go_id]}mappings filtered to the predicted accessions. Emits agt_restricted_to_predictedevent with before/after counts for the audit trail.
- protea.core.operations._run_cafa_data_helpers.restrict_data_to_protein_fold(data: EvaluationData, *, folds: int, fold: int, seed: int, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) EvaluationData#
Keep only proteins whose deterministic hash-fold equals
fold.A LEAN internal train/valid split for score HPO (A-SCORE.2 beat-pooled guard): the per-cell champion is selected on one fold and confirmed on the held-out fold, with no new EvaluationSet rows and no homology clustering. The fold is
blake2b(f"{seed}:{protein}") % foldsso it is stable across runs and independent of cell / config.folds <= 1returns the data unchanged.
- protea.core.operations._run_cafa_data_helpers.restrict_data_to_protein_set(data: EvaluationData, *, accessions: Collection[str], label: str, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) EvaluationData#
Keep only proteins named in
accessions.The general form of the fold restriction. A fold is a deterministic hash partition and answers “is this protein in slice N”; this answers “is this protein in a set someone computed elsewhere”, which is what a stratum needs. The strata in
protea.core.strataare resolved from the retrieved neighbourhood (length, homology, taxonomy, propagation gap), and none of those are derivable from the accession alone, so the membership has to arrive as data rather than as a predicate.labelnames the stratum in the emitted event. It is required because an unlabelled subset restriction produces a result that cannot be told from a full-population one afterwards, and this campaign has already lost a grid to exactly that.An empty
accessionsraises. Silently evaluating nothing and reporting a score over it is the failure this argument exists to prevent.
- protea.core.operations._run_cafa_data_helpers.restriction_fraction(before: int, after: int) float#
Share of the evaluation cohort the restriction removed.
- protea.core.operations._run_cafa_data_helpers.write_ground_truth_files(artifacts_root: Any, data: EvaluationData) dict[str, str]#
Write the five
gt_*.tsv/known_terms.tsvfiles used by cafaeval.Returns a dict
{label → path}so the caller can pass each path to the per-setting cafaeval driver.artifacts_rootis apathlib.Path(or anything convertible viastr); kept typed asAnyso the helper does not importpathlibjust for one signature.
- protea.core.operations._run_cafa_data_helpers.write_terms_of_interest(toi_path: str, toi_go_ids: list[str], *, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) None#
Persist the CAFA6 terms-of-interest file (one GO id per line, sorted).
cafaeval’s
-toiflag restricts evaluation to this set so that terms not in the frozen pivot graph (e.g. new since t-1) are excluded from scoring.
Per-setting cafaeval driver extracted from
RunCafaEvaluationOperation.execute.
- Wraps the per-setting (NK / LK / PK) loop that:
writes per-setting prediction TSVs (when a reranker applies),
invokes
cafaeval.evaluation.cafa_evalwith signal-safe handlers (default SIGTERM/SIGINT during the fork pool), which only applies on the main thread – see_default_signals_where_possible(),parses the dfs_best result,
writes the full cafaeval artifact tree per setting,
emits the
setting_done/setting_failedaudit events.
The helper takes the operation’s emit callback as a parameter
to keep the audit trail unchanged.
- class protea.core.operations._run_cafa_eval_driver.CafaEvalRunContext(pred_set_id: UUID, delta_proteins: set[str], max_distance: float | None, artifacts_root: Path, has_rerankers: bool, reranker_models: dict[str, dict[str, dict[str, Any]]], scoring_config_snapshot: ScoringConfig | None, data: EvaluationData, obo_path: str, nk_path: str, lk_path: str, pk_path: str, pk_known_path: str, ia_path: str | None, toi_path: str, shared_pred_dir: str, ontology_snapshot_id: str | None = None, evaluation_set_id: str | None = None, information_accretion_frame: str | None = None, th_step: float = 0.01, score_reading: str = 'raw', max_terms: int | None = None, max_k_position: int | None = None, max_sequence_rank: int | None = None, softprop: bool = False, interpro_graft: bool = False, interpro_protein2ipr_file: str | None = None, interpro_ipr2go_file: str | None = None, interpro_graft_weight: float | None = None)#
Bases:
objectBundle of per-run inputs consumed by
evaluate_all_settings().Groups the 16 per-call inputs (artifact paths, reranker bundles, delta cohort, scoring snapshot) so the entry-point signature stays under flake8-bugbear’s parameter ceiling.
- artifacts_root: Path#
- data: EvaluationData#
- delta_proteins: set[str]#
- evaluation_set_id: str | None = None#
- has_rerankers: bool#
- ia_path: str | None#
- information_accretion_frame: str | None = None#
Which information-accretion table, as a UUID when the run named a set, a content hash when it passed a bare file or the snapshot’s URL, and the literal “null” only when there was no IA table at all, in which case there is no weighted variant either.
- interpro_graft: bool = False#
- interpro_graft_weight: float | None = None#
- interpro_ipr2go_file: str | None = None#
- interpro_protein2ipr_file: str | None = None#
- lk_path: str#
- max_distance: float | None#
- max_k_position: int | None = None#
- max_sequence_rank: int | None = None#
The same depth counted in distinct sequences. Exactly one of the two is set;
_depth_unit_guardrefuses a run that names both or that names this one against candidates that cannot answer in it.
- max_terms: int | None = None#
- nk_path: str#
- obo_path: str#
- ontology_snapshot_id: str | None = None#
- pk_known_path: str#
- pk_path: str#
- pred_set_id: UUID#
- reranker_models: dict[str, dict[str, dict[str, Any]]]#
- score_reading: str = 'raw'#
How the prediction files are read before thresholding (ADR-D55). Applied once per file: the shared file at staging, a per-setting file here, after the arms that rewrite it.
- scoring_config_snapshot: ScoringConfig | None#
- softprop: bool = False#
- th_step: float = 0.01#
- toi_path: str#
- exception protea.core.operations._run_cafa_eval_driver.SettingEvaluationError#
Bases:
RuntimeErrorRaised when one or more NK/LK/PK settings produced no metrics.
Before this existed, a setting that raised was recorded as a warning and contributed
{}to the result, so a run where every setting failed still reported success and persisted anEvaluationResultwhose three cells were empty. An evaluation with no metrics in it is not a result, and a job that says it succeeded is the one place the absence cannot be seen.
- protea.core.operations._run_cafa_eval_driver.evaluate_all_settings(session: Session, *, ctx: CafaEvalRunContext, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) dict[str, dict[str, Any]]#
Drive the per-setting NK / LK / PK cafaeval loop.
Writes per-setting predictions when a reranker applies (otherwise reuses
ctx.shared_pred_dir), invokes cafaeval, parses results, persists the full cafaeval artifact tree, and emits per-setting audit events. Returns{setting → namespace metrics dict}.Raises
SettingEvaluationErrorwhen any setting produced no metrics, after all three have run and emitted their events.
Pure-function helpers extracted from run_cafa_evaluation.
Module-level utilities live here so the operation file
(run_cafa_evaluation.py) can stay focused on the orchestrator
class and shrink toward the master-plan v3.2 §3 LOC ceiling.
Re-exported by run_cafa_evaluation for backwards compatibility
with existing imports (_NS_LABELS, _NS_SHORT,
RunCafaEvaluationOperation, RunCafaEvaluationPayload).
- class protea.core.operations._run_cafa_helpers.ResultRow(result_id: uuid.UUID, inputs: Any, payload: dict[str, Any], scoring_config_id: str | None, first_reranker_id: Any, reranker_config_snapshot: Any, results: Any, provenance: tuple[Any, Any, Any, Any], max_sequence_rank: int | None = None, max_k_position: int | None = None)#
Bases:
NamedTupleEverything the stored EvaluationResult row is assembled from.
A bundle rather than twelve parameters, which is the same reason
AdapterInputsexists: the ceiling is six and the row genuinely has twelve fields.- first_reranker_id: Any#
Alias for field number 4
- inputs: Any#
Alias for field number 1
- max_k_position: int | None#
Alias for field number 9
- max_sequence_rank: int | None#
The depth this result scored, in whichever unit was asked for. Both None means the whole stored neighbourhood. These are the fields a reader comes looking for: they say which cut produced these numbers, and until 2026-08-30 nothing on the row said it, so a five point depth series rendered as five results at the retrieval depth of 30.
- payload: dict[str, Any]#
Alias for field number 2
- provenance: tuple[Any, Any, Any, Any]#
(frame, temporal_window, leakage_role, arms_enabled), kept as the tuple its producer returns rather than unpacked and re-packed. Four names that always travel together are one thing.
- reranker_config_snapshot: Any#
Alias for field number 5
- result_id: UUID#
Alias for field number 0
- results: Any#
Alias for field number 6
- scoring_config_id: str | None#
Alias for field number 3
- protea.core.operations._run_cafa_helpers.build_result_row(row: ResultRow) EvaluationResult#
The stored row, assembled in one place.
- protea.core.operations._run_cafa_helpers.eval_artifact_key(result_id: UUID, relpath: str) str#
Canonical MinIO/artifact-store key for a cafaeval output file.
Reranker-model loader extracted from run_cafa_evaluation.execute.
Resolves stored RerankerModel rows into the nested
{setting → aspect → {"model": str, "cat_codes": dict|None}}
bundle the rest of the operation consumes. Supports both the legacy
inline model_data blob and the artifact_uri (artifact-store)
path that lab-trained boosters use.
The function takes the operation’s emit callback as a parameter
so it can keep the same audit-trail events (reranker_loaded)
without coupling the helper module to the worker’s event types.
- protea.core.operations._run_cafa_reranker_loader.load_reranker_models_for_payload(session: Session, *, rerankers_nested: dict[str, dict[str, str]] | None, reranker_id_nk: str | None, reranker_id_lk: str | None, reranker_id_pk: str | None, emit: Callable[[str, str | None, dict[str, Any], Literal['info', 'warning', 'error']], None]) tuple[dict[str, dict[str, dict[str, Any]]], dict[str, dict[str, str]] | None]#
Resolve every payload reranker reference into the nested bundle dict.
- Two branches:
rerankers_nested(new payload field): per-category + per-aspect mapping, one model per (NK/LK/PK, P/F/C) cell.Legacy flat fields
reranker_id_{nk,lk,pk}: one model per category, applied to all aspects (key"").
Returns
(reranker_models, reranker_config_snapshot)where the snapshot is the nested-form representation suitable for persisting inEvaluationResult.reranker_config(Nonefor the legacy flat path).
- protea.core.operations._run_cafa_reranker_loader.resolve_reranker_model_bundle(rm: RerankerModel) dict[str, Any]#
Return
{"model": str, "cat_codes": dict|None, "universal": dict|None}from either the legacy inline blob or theartifact_uricache.Boosters trained by the lab and imported via
/reranker-models/importonly setartifact_uriand leavemodel_dataNULL, so the operation must transparently support both paths.cat_codes(if present in the imported run.json under__categorical_codes__) is the lab’s per-column sorted-unique string vocabulary, used at predict time to reproduce the encoding seen during training. Without it,reranker_predictfalls back topd.factorizeover the inference batch, which silently produces the wrong codes for per-aspect inference and tanks the LK / PK fmax. Seeprotea.core.reranker.predict().universalcarries the universal-booster scoring context ({"categorical_codes", "plm_id", "k_context"}) recovered from the booster’s siblingrun.json. It is non-Noneonly when the artifact-store booster is a universal (pooled, K-augmented) model (detected byis_universal_booster()); such boosters carry injectedplm_id/k_contextfeature columns that the genericreranker_predictcannot encode, so the eval-artifacts writers route them throughscore_universal()instead. Legacy inline boosters never take the universal path (universal models are always imported by reference), souniversalisNonefor themodel_databranch.
Setup-phase helpers extracted from run_cafa_evaluation.
Holds the two NamedTuple bundles threaded through the run pipeline
plus the small functions that load the term universe and emit the
setup events. Living in a sibling keeps the operation file lean and
under the master-plan v3.2 §3 LOC budget.
Re-exported by run_cafa_evaluation for backwards compatibility.
- class protea.core.operations._run_cafa_setup.StagedInputs(obo_path: str, ia_path: str | None, gt_paths: dict[str, str], toi_path: str, data: Any, delta_proteins: set[str], has_rerankers: bool)#
Bases:
NamedTupleWhat the staging step produced, named.
It had no name, so the function that consumes it took eleven arguments and the size guard was right to object: a parameter list that long is usually a missing noun. These seven values are exactly what staging writes or resolves, and nothing else in the pipeline produces them.
- data: Any#
Alias for field number 4
- delta_proteins: set[str]#
Alias for field number 5
- gt_paths: dict[str, str]#
Alias for field number 2
- has_rerankers: bool#
Alias for field number 6
- ia_path: str | None#
Alias for field number 1
- obo_path: str#
Alias for field number 0
- toi_path: str#
Alias for field number 3
- protea.core.operations._run_cafa_setup.TOI_RULES: tuple[str, ...] = ('pivot_terms', 'live_in_both_ends')#
The terms-of-interest rules, by the name a payload asks for them with.
pivot_termsis what the platform has always done and stays the default, so no stored result moves and no frame changes under anyone.live_in_both_endsis the rule the lab’s long window uses, and it differs from the default twice over. It drops the obsolete, which the default keeps: the pivot of the 211 -> 227 window carries 47,328 terms of which 3,770 are obsolete, and cafaeval’s ownobo_parserexcludes obsolete terms from the graphs it builds, so the default hands the scorer a universe 3,770 terms wider than anything it can score. And it consults BOTH ends rather than one: a term obsolete by t1 is scored by the default as though it still existed. On that window the two rules are 43,558 terms against 39,028.
- protea.core.operations._run_cafa_setup.bundle_run_context(p: RunCafaEvaluationPayload, ctx: _PipelineCtx, artifacts_root: Path, staged: StagedInputs, emit: EmitFn) CafaEvalRunContext#
Name what was staged, and nothing else.
Every field here is a value the staging step already produced, so this is the one place where a caller can see the whole cafaeval input surface at once, including the three frame markers that have to travel with the grid artefact or two runs under different frames publish as a method difference.
Sibling helper for RunCafaEvaluationOperation.summarize_payload.
Builds the per-job CLI / event summary that the jobs router exposes.
Lives outside run_cafa_evaluation.py so the operation module stays
under §3 file-LOC budget. Each _bits_from_* helper is a small,
test-friendly chunk.
- protea.core.operations._run_cafa_summary.summarize_payload(payload: dict[str, Any], session: Session | None) str#
Build the human-readable run summary for the CAFA evaluator.
Mirrors the Job summarize_payload contract: never raises, falls back to UUID prefixes when a FK row is missing or no session is available.
See also
Operations: narrative documentation for every operation listed above, with payload examples and execution flow.
Infrastructure: the ORM models that
protea.corereads and writes.How-to Guides: task-oriented recipes that exercise these modules end-to-end.