Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions horizon/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions horizon/pipeline/assets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -95,6 +96,7 @@
"delivery_metrics",
"member_scores",
"member_scores_integrity",
"member_explanations",
"publish_ranking",
"publish_ranking_integrity",
]
102 changes: 102 additions & 0 deletions horizon/pipeline/assets/ranking_explanations.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 3 additions & 3 deletions horizon/pipeline/assets/ranking_publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand All @@ -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)


Expand Down
11 changes: 11 additions & 0 deletions horizon/pipeline/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 2 additions & 0 deletions horizon/pipeline/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
review_and_rating_metrics,
member_scores,
member_scores_integrity,
member_explanations,
publish_ranking,
publish_ranking_integrity,
)
Expand Down Expand Up @@ -88,6 +89,7 @@
review_and_rating_metrics,
delivery_metrics,
member_scores,
member_explanations,
publish_ranking,
],
asset_checks=[
Expand Down
7 changes: 7 additions & 0 deletions horizon/pipeline/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
5 changes: 4 additions & 1 deletion horizon/tests/test_pipeline_definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
AssetKey("review_and_rating_metrics"),
AssetKey("delivery_metrics"),
AssetKey("member_scores"),
AssetKey("member_explanations"),
AssetKey("publish_ranking"),
}

Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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",
}

Expand Down
82 changes: 82 additions & 0 deletions horizon/tests/test_ranking_explanations_db.py
Original file line number Diff line number Diff line change
@@ -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}
2 changes: 2 additions & 0 deletions horizon/tests/test_ranking_publish_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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


Expand Down
Loading