From 9c1e378eb101ac1cb81fbd52a99a50d8c5d741a9 Mon Sep 17 00:00:00 2001 From: Yash Ponnaganti Date: Fri, 20 Nov 2026 14:39:21 -0500 Subject: [PATCH] T4.6: member_explanations asset, explanation cache and published notes Runs after member_scores and before publish_ranking. Each scored member's explanation, the model that wrote it, the prompt version and the input's sha256 go on its member_scores row (three additive columns). A member whose input is unchanged reuses an earlier generated explanation instead of calling the API; fallbacks are never reused, so they are replaced once a key is set. The API calls run outside any transaction. publish_ranking copies the summary and data gaps into document.explanation and each note into its bucket. ANTHROPIC_API_KEY and HORIZON_ANTHROPIC_MODEL are read through PipelineSettings and documented in .env.example; without a key every member gets the deterministic fallback and publishing still runs. --- horizon/.env.example | 5 + horizon/pipeline/assets/__init__.py | 2 + .../pipeline/assets/ranking_explanations.py | 102 ++++++++++++++++++ horizon/pipeline/assets/ranking_publish.py | 6 +- horizon/pipeline/config.py | 11 ++ horizon/pipeline/definitions.py | 2 + horizon/pipeline/schema.sql | 7 ++ horizon/tests/test_pipeline_definitions.py | 5 +- horizon/tests/test_ranking_explanations_db.py | 82 ++++++++++++++ horizon/tests/test_ranking_publish_db.py | 2 + 10 files changed, 220 insertions(+), 4 deletions(-) create mode 100644 horizon/pipeline/assets/ranking_explanations.py create mode 100644 horizon/tests/test_ranking_explanations_db.py diff --git a/horizon/.env.example b/horizon/.env.example index 802f9bc8..bd9a9bb0 100644 --- a/horizon/.env.example +++ b/horizon/.env.example @@ -14,3 +14,8 @@ HORIZON_AUTHENTIK_API_TOKEN= # Postgres feature store. Use the legacy Horizon deploy/Supabase connection URL # here or export GITEA_ANALYTICS_DATABASE_URL in the deployment environment. HORIZON_DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/DATABASE + +# T4.6 ranking explanations. Without a key every member gets a deterministic +# summary of their numbers (generated=false) and publishing still runs. +ANTHROPIC_API_KEY= +HORIZON_ANTHROPIC_MODEL=claude-sonnet-5-5 diff --git a/horizon/pipeline/assets/__init__.py b/horizon/pipeline/assets/__init__.py index 4ab6bb37..521d4ed2 100644 --- a/horizon/pipeline/assets/__init__.py +++ b/horizon/pipeline/assets/__init__.py @@ -52,6 +52,7 @@ ranking_run, review_and_rating_metrics, ) +from .ranking_explanations import member_explanations from .ranking_publish import publish_ranking, publish_ranking_integrity from .ranking_scores import member_scores, member_scores_integrity from .source import RepositoryConfig, authentik_users, gitea_repository @@ -95,6 +96,7 @@ "delivery_metrics", "member_scores", "member_scores_integrity", + "member_explanations", "publish_ranking", "publish_ranking_integrity", ] diff --git a/horizon/pipeline/assets/ranking_explanations.py b/horizon/pipeline/assets/ranking_explanations.py new file mode 100644 index 00000000..c935bd28 --- /dev/null +++ b/horizon/pipeline/assets/ranking_explanations.py @@ -0,0 +1,102 @@ +"""T4.6: plain-language explanations for a scored run, before it is published.""" + +# No `from __future__ import annotations` (see ranking.py). +from collections import Counter + +from dagster import AssetExecutionContext, Failure, MetadataValue, asset +from psycopg.types.json import Jsonb + +from ..config import get_pipeline_settings +from ..ranking import explanations, score_store, store +from ..storage import PostgresResource +from .ranking import RankingRun, _run_rubric + + +@asset( + group_name="08_ranking", + kinds={"python", "postgres"}, + description=( + "Writes a short explanation of every scored member's numbers to " + "member_scores.explanation. The model sees only that member's own numbers. " + "An unchanged input reuses an earlier run's explanation; without an API key, " + "or after a second invalid answer, a summary of the numbers is stored instead." + ), + metadata={"table": "horizon_ranking.member_scores"}, +) +def member_explanations( + context: AssetExecutionContext, + ranking_run: RankingRun, + member_scores: int, + postgres: PostgresResource, +) -> int: + del member_scores + settings = get_pipeline_settings() + client = explanations.make_client(settings.anthropic_api_key) + return explain_run(context, ranking_run, postgres, client, settings.anthropic_model) + + +def _cached(connection, sha: str): + """An earlier generated explanation of the same input; fallbacks are never reused.""" + + row = connection.execute( + """ + SELECT explanation FROM horizon_ranking.member_scores + WHERE input_sha256 = %s AND prompt_version = %s + AND (explanation->>'generated')::boolean + LIMIT 1 + """, + (sha, explanations.PROMPT_VERSION), + ).fetchone() + return row[0] if row else None + + +def explain_run(context, ranking_run: RankingRun, postgres: PostgresResource, client, model: str) -> int: + rubric = _run_rubric(ranking_run).rubric + run_id = ranking_run.ranking_run_id + with postgres.connect() as connection: + run = score_store.read_run(connection, run_id) + if run.status == "published": + context.add_output_metadata({"retry": MetadataValue.text("already published; unchanged")}) + return 0 + if run.status != "scored": + raise Failure(description=f"Ranking run {run_id} is {run.status}; explanations need a scored run.") + members = store.read_ranked_members(connection, run_id) + scores = score_store.read_scores(connection, run_id) + metrics = score_store.read_scored_metrics(connection, run_id) + group_sizes = Counter(member.comparison_group for member in members) + work = [] + for member in members: + key = (member.authentik_user_pk, member.project_pk) + data = explanations.explanation_input( + member, rubric.roles[member.role], scores[key], metrics[key], + group_sizes[member.comparison_group], + ) + sha = explanations.input_sha256(data) + work.append((key, data, sha, _cached(connection, sha))) + + # The API calls run outside any transaction so no row stays locked meanwhile. + fresh = explanations.explain_all(client, model, [data for _, data, _, cached in work if cached is None]) + results, sources = [], Counter() + for key, _data, sha, cached in work: + result = cached if cached is not None else fresh.pop(0) + sources["cached" if cached is not None else "generated" if result["generated"] else "fallback"] += 1 + results.append((Jsonb(result), result["model"], explanations.PROMPT_VERSION, sha, run_id, *key)) + + with postgres.connect() as connection: + if score_store.read_run(connection, run_id, lock=True).status != "scored": + raise Failure(description=f"Ranking run {run_id} changed status while it was being explained.") + with connection.cursor() as cursor: + cursor.executemany( + """ + UPDATE horizon_ranking.member_scores + SET explanation = %s, explanation_model = %s, prompt_version = %s, input_sha256 = %s + WHERE ranking_run_id = %s AND authentik_user_pk = %s AND project_pk = %s + """, + results, + ) + context.add_output_metadata({ + "ranking_run_id": MetadataValue.text(run_id), + "explanations": MetadataValue.json(dict(sources)), + "model": MetadataValue.text(model if client is not None else "none (no API key)"), + }) + return len(results) diff --git a/horizon/pipeline/assets/ranking_publish.py b/horizon/pipeline/assets/ranking_publish.py index ba8f974b..b3263cfc 100644 --- a/horizon/pipeline/assets/ranking_publish.py +++ b/horizon/pipeline/assets/ranking_publish.py @@ -13,7 +13,7 @@ group_name="08_ranking", kinds={"postgres"}, description=( - "Publishes a scored run in one transaction: replaces its leaderboard rows and " + "Publishes a scored, explained run in one transaction: replaces its leaderboard rows and " "member documents in horizon_api, moves the semester's ranking publication " "to it (keeping the old run as previous_run_id) and marks it published. On " "any error the run is marked failed and the previous publication stays." @@ -23,10 +23,10 @@ def publish_ranking( context: AssetExecutionContext, ranking_run: RankingRun, - member_scores: int, + member_explanations: int, postgres: PostgresResource, ) -> int: - del member_scores + del member_explanations return _publish(context, ranking_run, postgres) diff --git a/horizon/pipeline/config.py b/horizon/pipeline/config.py index 76ff9946..ce0ac2e0 100644 --- a/horizon/pipeline/config.py +++ b/horizon/pipeline/config.py @@ -87,6 +87,17 @@ class PipelineSettings(BaseSettings): ), description="Postgres URL for the Horizon ownership feature store.", ) + anthropic_api_key: str | None = Field( + default=None, + repr=False, + validation_alias=AliasChoices("ANTHROPIC_API_KEY", "HORIZON_ANTHROPIC_API_KEY"), + description="Anthropic API key for T4.6 ranking explanations; unset means fallbacks only.", + ) + anthropic_model: str = Field( + default="claude-sonnet-5-5", + validation_alias=AliasChoices("HORIZON_ANTHROPIC_MODEL"), + description="Model for T4.6 ranking explanations.", + ) def require_gitea_url(self) -> str: return _required(self.gitea_url, "HORIZON_GITEA_URL") diff --git a/horizon/pipeline/definitions.py b/horizon/pipeline/definitions.py index 54cf08e8..22e9e699 100644 --- a/horizon/pipeline/definitions.py +++ b/horizon/pipeline/definitions.py @@ -39,6 +39,7 @@ review_and_rating_metrics, member_scores, member_scores_integrity, + member_explanations, publish_ranking, publish_ranking_integrity, ) @@ -88,6 +89,7 @@ review_and_rating_metrics, delivery_metrics, member_scores, + member_explanations, publish_ranking, ], asset_checks=[ diff --git a/horizon/pipeline/schema.sql b/horizon/pipeline/schema.sql index 0cff9361..a36e770c 100644 --- a/horizon/pipeline/schema.sql +++ b/horizon/pipeline/schema.sql @@ -475,6 +475,13 @@ CREATE TABLE IF NOT EXISTS horizon_ranking.member_scores ( ); CREATE INDEX IF NOT EXISTS member_scores_member_history ON horizon_ranking.member_scores (authentik_user_pk, ranking_run_id); +-- T4.6: what produced member_scores.explanation. A later run whose member has +-- the same input_sha256 and prompt_version copies the explanation. +ALTER TABLE horizon_ranking.member_scores ADD COLUMN IF NOT EXISTS explanation_model TEXT; +ALTER TABLE horizon_ranking.member_scores ADD COLUMN IF NOT EXISTS prompt_version TEXT; +ALTER TABLE horizon_ranking.member_scores ADD COLUMN IF NOT EXISTS input_sha256 TEXT; +CREATE INDEX IF NOT EXISTS member_scores_explanation_cache + ON horizon_ranking.member_scores (input_sha256, prompt_version); -- Written by the T4.6 CLI and the T6.7 API. CREATE TABLE IF NOT EXISTS horizon_ranking.calibration_notes ( diff --git a/horizon/tests/test_pipeline_definitions.py b/horizon/tests/test_pipeline_definitions.py index 2c6bf989..e28cfc1c 100644 --- a/horizon/tests/test_pipeline_definitions.py +++ b/horizon/tests/test_pipeline_definitions.py @@ -46,6 +46,7 @@ AssetKey("review_and_rating_metrics"), AssetKey("delivery_metrics"), AssetKey("member_scores"), + AssetKey("member_explanations"), AssetKey("publish_ranking"), } @@ -86,7 +87,8 @@ def deps_of(name): assert AssetKey("ranked_members") in deps_of("delivery_metrics") for metrics in ("code_and_tenure_metrics", "review_and_rating_metrics", "delivery_metrics"): assert AssetKey(metrics) in deps_of("member_scores") - assert AssetKey("member_scores") in deps_of("publish_ranking") + assert AssetKey("member_scores") in deps_of("member_explanations") + assert AssetKey("member_explanations") in deps_of("publish_ranking") def test_each_layer_is_its_own_group(): @@ -131,6 +133,7 @@ def test_each_layer_is_its_own_group(): "review_and_rating_metrics": "08_ranking", "delivery_metrics": "08_ranking", "member_scores": "08_ranking", + "member_explanations": "08_ranking", "publish_ranking": "08_ranking", } diff --git a/horizon/tests/test_ranking_explanations_db.py b/horizon/tests/test_ranking_explanations_db.py new file mode 100644 index 00000000..8c327f5b --- /dev/null +++ b/horizon/tests/test_ranking_explanations_db.py @@ -0,0 +1,82 @@ +from dagster import Failure +import pytest + +from pipeline.assets.ranking_explanations import explain_run +from pipeline.assets.ranking_publish import _publish +from pipeline.assets.ranking_scores import _score_run + +from ranking_db import FakeContext, needs_postgres, seed_worked_example +from test_ranking_explanations import BUCKETS, FakeClient, _answer + +pytestmark = needs_postgres + + +def _scored(postgres, dagster_run_id): + run = seed_worked_example(postgres, dagster_run_id=dagster_run_id) + _score_run(FakeContext(), run, postgres) + return run + + +def test_explanations_are_stored_and_published_into_the_document(ranking_postgres): + run = _scored(ranking_postgres, "dagster-a") + notes = {key: f"Note on {key}." for key in BUCKETS} + client = FakeClient(*[_answer(notes=notes) for _ in range(4)]) + context = FakeContext() + + assert explain_run(context, run, ranking_postgres, client, "claude-sonnet-5-5") == 4 + assert context.metadata["explanations"].data == {"generated": 4} + _publish(FakeContext(), run, ranking_postgres) + + with ranking_postgres.connect() as connection: + model, version, sha = connection.execute( + """SELECT explanation_model, prompt_version, input_sha256 FROM horizon_ranking.member_scores + WHERE authentik_user_pk = 'A'""" + ).fetchone() + document = connection.execute( + "SELECT document FROM horizon_api.ranking_member_detail WHERE authentik_user_pk = 'A'" + ).fetchone()[0] + assert (model, version, len(sha)) == ("claude-test", "explain-v1", 64) + assert document["explanation"] == {"summary": "Ada's numbers are in the middle of the group.", + "dataGaps": ["No owned SOW tasks yet."], "model": "claude-test", + "generated": True} + assert document["buckets"][0]["note"] == f"Note on {document['buckets'][0]['key']}." + for request in client.calls: + assert "Member A" not in request["messages"][0]["content"] + + +def test_an_unchanged_input_reuses_the_earlier_explanation(ranking_postgres): + first = _scored(ranking_postgres, "dagster-a") + explain_run(FakeContext(), first, ranking_postgres, FakeClient(*[_answer() for _ in range(4)]), "m") + _publish(FakeContext(), first, ranking_postgres) + second = _scored(ranking_postgres, "dagster-b") + client = FakeClient() + context = FakeContext() + + explain_run(context, second, ranking_postgres, client, "m") + + assert client.calls == [] and context.metadata["explanations"].data == {"cached": 4} + + +def test_without_a_client_every_member_gets_the_fallback(ranking_postgres): + run = _scored(ranking_postgres, "dagster-a") + context = FakeContext() + explain_run(context, run, ranking_postgres, None, "m") + assert context.metadata["explanations"].data == {"fallback": 4} + + +def test_a_running_run_is_not_explained(ranking_postgres): + run = seed_worked_example(ranking_postgres) + with pytest.raises(Failure, match="need a scored run"): + explain_run(FakeContext(), run, ranking_postgres, None, "m") + + +def test_fallbacks_are_not_reused_once_a_key_is_configured(ranking_postgres): + first = _scored(ranking_postgres, "dagster-a") + explain_run(FakeContext(), first, ranking_postgres, None, "m") + _publish(FakeContext(), first, ranking_postgres) + second = _scored(ranking_postgres, "dagster-b") + context = FakeContext() + + explain_run(context, second, ranking_postgres, FakeClient(*[_answer() for _ in range(4)]), "m") + + assert context.metadata["explanations"].data == {"generated": 4} diff --git a/horizon/tests/test_ranking_publish_db.py b/horizon/tests/test_ranking_publish_db.py index 2dc8983f..b9e1964c 100644 --- a/horizon/tests/test_ranking_publish_db.py +++ b/horizon/tests/test_ranking_publish_db.py @@ -3,6 +3,7 @@ import pytest from dagster import Failure +from pipeline.assets.ranking_explanations import explain_run from pipeline.assets.ranking_publish import _publish from pipeline.assets.ranking_scores import _score_run from pipeline.ranking import publish, score_store @@ -16,6 +17,7 @@ def _scored(postgres, dagster_run_id, as_of=AS_OF, scale=1.0): run = seed_worked_example(postgres, dagster_run_id=dagster_run_id, as_of=as_of, scale=scale) _score_run(FakeContext(), run, postgres) + explain_run(FakeContext(), run, postgres, None, "none") return run