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
54 changes: 54 additions & 0 deletions horizon/dev/t4-staging/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Track 4 on staging

Runs the whole ranking graph (`ranking_run` through `publish_ranking`, with its
asset checks) against a throwaway Postgres on the staging box, using a synthetic
FALL 2026 semester. The input tables owned by unmerged tracks (T1.1, T2.5, T2.6,
T3.4, T5.x) come from `inputs.sql`, a copy of their deployed definitions, so
this tests Track 4 against the production table shapes.

From your Mac, in the TechOps clone (the branch does not need to be pushed):

```
git show t4/7c-staging-runner:horizon/dev/t4-staging/ship-to-staging.sh > /tmp/ship-t4.sh
bash /tmp/ship-t4.sh # seed, run, check
bash /tmp/ship-t4.sh t4/7c-staging-runner -- --tests --ui
bash /tmp/ship-t4.sh t4/7c-staging-runner -- --down
```

`ship-to-staging.sh` copies the branch's committed `horizon/` folder to
`/opt/horizon-t4/<branch>` on the box over one `ssh appdev-staging`
connection, runs `run-on-staging.sh` there and copies the compare report back.
On the box itself:

```
bash dev/t4-staging/run-on-staging.sh [--tests] [--ui]
bash dev/t4-staging/run-on-staging.sh --down
```

The run ends with "All expected results hold." and exit code 0, or lists what
came out wrong and exits 1. It checks:

- the seeded cases: who is ranked and how, `group_too_small`,
`insufficient_data`, `no_sow`, the excluded review bucket, explanations;
- metric values: `seed.py` works out files owned, surviving commits, active
weeks, the longest inactive stretch, PRs reviewed, review turnaround,
collaborative PRs, delivery and every survey rating from the seeded rows with
the card formulas, and the run must match each one exactly.

Run on the code from before the T4.2/T4.3 fixes, the value checks fail on
collaborative PRs (Co-authored-by trailers), engineer and tech lead ratings
(respondent roles), the longest inactive stretch (the gap since the last
activity) and review turnaround (the daylight-saving hour).

- Creates only `horizon-t4-*` containers, a `horizon-t4` network and a
`horizon-t4-venv` volume. Postgres publishes no port; the Dagster UI (`--ui`)
binds 127.0.0.1:3070. Nothing in the Coolify stack is touched.
- Every run starts from an empty database. The password is generated into
`.pg-password` (git-ignored) and removed by `--down`.
- Explanations use deterministic fallbacks unless `ANTHROPIC_API_KEY` is set
in the shell. Staging rules: do not use a real key there.
- A v1 run is scored next to the published v2 run (v1 has the survey buckets),
and the admin compare report is written to `out/`.

Locally, without Docker: create a database, then
`HORIZON_DATABASE_URL=... python dev/t4-staging/seed.py && python dev/t4-staging/run_t4.py --compare-v1`.
90 changes: 90 additions & 0 deletions horizon/dev/t4-staging/run-on-staging.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
# Run Track 4 end to end on the staging box, in its own containers.
#
# bash run-on-staging.sh seed a fresh database and run the graph
# bash run-on-staging.sh --tests also run the pytest suite, database tests included
# bash run-on-staging.sh --ui also start Dagster on 127.0.0.1:3070 (tunnel to view)
# bash run-on-staging.sh --down remove everything this script created
#
# It creates only horizon-t4-* containers, a horizon-t4 network and a
# horizon-t4-venv volume. Postgres publishes no port; Dagster binds 127.0.0.1.
# It never touches the Coolify stack, its postgres, or /opt/pp-deploy.
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
HORIZON="$(cd "$HERE/../.." && pwd)"
NET=horizon-t4
PG=horizon-t4-pg
UI=horizon-t4-dagster
VENV=horizon-t4-venv
PY_IMAGE=python:3.11-slim
SECRET="$HERE/.pg-password"

down() {
docker rm -f "$PG" "$UI" >/dev/null 2>&1 || true
docker network rm "$NET" >/dev/null 2>&1 || true
rm -f "$SECRET"
}

TESTS=0 UI_ON=0
for arg in "$@"; do
case "$arg" in
--down) down; docker volume rm "$VENV" >/dev/null 2>&1 || true
echo "Removed the horizon-t4 containers, network and volume."; exit 0 ;;
--tests) TESTS=1 ;;
--ui) UI_ON=1 ;;
*) echo "unknown option: $arg" >&2; exit 2 ;;
esac
done

# Always start from an empty database so the seed is the only data.
down
umask 077
head -c 18 /dev/urandom | base64 | tr -d '/+=' > "$SECRET"
PASSWORD="$(cat "$SECRET")"
URL="postgresql://horizon:${PASSWORD}@${PG}:5432/horizon"

docker network create "$NET" >/dev/null
docker volume create "$VENV" >/dev/null 2>&1 || true
docker run -d --name "$PG" --network "$NET" --restart unless-stopped \
-e POSTGRES_USER=horizon -e POSTGRES_PASSWORD="$PASSWORD" -e POSTGRES_DB=horizon \
postgres:16 >/dev/null
echo -n "Waiting for Postgres"
until docker exec "$PG" pg_isready -U horizon -d horizon >/dev/null 2>&1; do echo -n .; sleep 1; done
echo " ready."

py() {
docker run --rm --network "$NET" -v "$HORIZON:/src" -v "$VENV:/venv" -w /src \
-e HORIZON_ENV_FILE= -e HORIZON_DATABASE_URL="$URL" \
-e TEST_POSTGRES_URL="postgresql://horizon:${PASSWORD}@${PG}:5432/postgres" \
-e ANTHROPIC_API_KEY="${ANTHROPIC_API_KEY:-}" -e PYTHONDONTWRITEBYTECODE=1 \
"$@"
}

echo "Installing the pipeline (cached in the $VENV volume until pyproject.toml changes)..."
py "$PY_IMAGE" bash -c 'want=$(sha256sum pyproject.toml | cut -c1-16)
[ "$(cat /venv/.installed 2>/dev/null)" = "$want" ] && exit 0
[ -x /venv/bin/python ] || python -m venv /venv
/venv/bin/pip install -q -e ".[test,pipeline,orchestration]" && echo "$want" > /venv/.installed'

echo "Seeding a synthetic FALL 2026 semester..."
py "$PY_IMAGE" /venv/bin/python dev/t4-staging/seed.py

echo "Running ranking_run through publish_ranking..."
py "$PY_IMAGE" bash -c 'set -o pipefail; /venv/bin/python dev/t4-staging/run_t4.py --compare-v1 2>&1 | grep -vE "dagster - (DEBUG|INFO)"'
echo "v1 vs v2 compare report: $HERE/out/"

if [ "$TESTS" = 1 ]; then
echo "Running the test suite (database tests included)..."
py "$PY_IMAGE" /venv/bin/python -m pytest -q -p no:cacheprovider tests
fi

if [ "$UI_ON" = 1 ]; then
docker run -d --name "$UI" --network "$NET" -p 127.0.0.1:3070:3070 \
-v "$HORIZON:/src" -v "$VENV:/venv" -w /src \
-e HORIZON_ENV_FILE= -e HORIZON_DATABASE_URL="$URL" -e DAGSTER_HOME=/tmp/dagster-home \
"$PY_IMAGE" bash -c 'mkdir -p $DAGSTER_HOME && /venv/bin/dagster-webserver -h 0.0.0.0 -p 3070 -m pipeline.definitions' >/dev/null
echo "Dagster UI on the box at 127.0.0.1:3070. From your Mac:"
echo " ssh -N -L 3070:127.0.0.1:3070 appdev-staging then open http://localhost:3070"
fi
echo "Done. Remove everything with: bash $0 --down"
205 changes: 205 additions & 0 deletions horizon/dev/t4-staging/run_t4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
"""Run the whole Track 4 graph against a seeded database and print what it produced.

HORIZON_DATABASE_URL=postgresql://... python dev/t4-staging/run_t4.py [--compare-v1]

Materializes ranking_run through publish_ranking with their asset checks, in
one Dagster run (rubric v2, as_of from seed.py), then prints the leaderboard,
one member document and the check results, then checks the seeded cases
(exit code 1 if any is wrong). --compare-v1 also scores a v1 run (not
published) and writes the admin compare report next to this file.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

from dagster import DagsterInstance, materialize

from pipeline.assets import (
code_and_tenure_metrics, delivery_metrics, feature_store_schema, member_explanations,
member_scores, member_scores_integrity, publish_ranking, publish_ranking_integrity,
ranked_members, ranking_run, review_and_rating_metrics,
)
from pipeline.config import get_pipeline_settings
from pipeline.ranking import admin
from pipeline.storage import PostgresResource

sys.path.insert(0, str(Path(__file__).parent))
from seed import AS_OF, SEASON # noqa: E402

THROUGH_SCORES = [feature_store_schema, ranking_run, ranked_members, code_and_tenure_metrics,
review_and_rating_metrics, delivery_metrics, member_scores, member_scores_integrity]
FULL = THROUGH_SCORES + [member_explanations, publish_ranking, publish_ranking_integrity]


def run(postgres: PostgresResource, rubric: str, assets) -> str:
config = {"ops": {"ranking_run": {"config": {
"season_type": SEASON[0], "season_year": SEASON[1], "as_of": AS_OF.isoformat(), "rubric_version": rubric,
}}}}
result = materialize(assets, resources={"postgres": postgres}, run_config=config,
instance=DagsterInstance.ephemeral(), raise_on_error=False)
print(f"\n== Dagster run, rubric {rubric}: {'SUCCESS' if result.success else 'FAILED'}")
for event in result.all_events:
if event.event_type_value == "STEP_FAILURE":
print(f" step failed: {event.step_key}: {event.event_specific_data.error.message.strip()}")
if event.event_type_value == "ASSET_CHECK_EVALUATION":
check = event.event_specific_data
print(f" check {check.check_name}: {'passed' if check.passed else 'FAILED'} - {check.description}")
with postgres.connect() as connection:
run_id, status, reason = connection.execute(
"""SELECT ranking_run_id::text, status, failure_reason FROM horizon_ranking.ranking_runs
WHERE rubric_version = %s ORDER BY created_at DESC LIMIT 1""", (rubric,)).fetchone()
print(f" ranking run {run_id}: {status}" + (f" ({reason})" if reason else ""))
if not result.success:
raise SystemExit(1)
return run_id


def report(postgres: PostgresResource, run_id: str) -> None:
with postgres.connect() as connection:
rows = connection.execute(
"""SELECT comparison_group_label, rank_in_group, ranked_in_group, display_name, status,
round(overall_score::numeric, 1), round(coverage::numeric, 2)
FROM horizon_api.ranking_leaderboard WHERE ranking_run_id = %s
ORDER BY comparison_group_label, rank_in_group NULLS LAST, display_name""", (run_id,)).fetchall()
document = connection.execute(
"""SELECT document FROM horizon_api.ranking_member_detail
WHERE ranking_run_id = %s AND project_pk = 'p-beacon' ORDER BY authentik_user_pk LIMIT 1""",
(run_id,)).fetchone()[0]
pointer = connection.execute(
"SELECT run_id FROM horizon_api.publications WHERE domain = 'ranking'").fetchone()[0]
print(f"\n== Leaderboard (publication points at {'this run' if pointer == run_id else pointer})")
group = None
for label, rank, of, name, status, score, coverage in rows:
if label != group:
print(f" {label}")
group = label
place = f"{rank}/{of}" if rank else "-"
print(f" {place:>5} {name:<14} {status:<18} score {score if score is not None else '-':>5} coverage {coverage}")
print("\n== Member document (Beacon, review bucket switched off)")
print(" buckets: " + ", ".join(f"{b['key']} {b['weight']:.2f}" for b in document["buckets"]))
print(" explanation: " + json.dumps(document["explanation"])[:400])


def _expect(problems: list[str], ok: bool, what: str) -> None:
print(f" {'ok ' if ok else 'FAIL'} {what}")
if not ok:
problems.append(what)


def verify(postgres: PostgresResource, run_id: str) -> list[str]:
"""Check each case the seed was built to show."""

print("\n== Expected results")
problems: list[str] = []
with postgres.connect() as connection:
def one(query, *params):
return connection.execute(query, (run_id, *params)).fetchone()

def reason(name, metric):
row = one("""SELECT v.missing_reason FROM horizon_ranking.metric_values v
JOIN horizon_ranking.ranked_members m USING (ranking_run_id, authentik_user_pk, project_pk)
WHERE v.ranking_run_id = %s AND m.display_name = %s AND v.metric_key = %s""", name, metric)
return row[0] if row else "<no row>"

def status(name):
row = one("""SELECT status FROM horizon_api.ranking_leaderboard
WHERE ranking_run_id = %s AND display_name = %s""", name)
return row[0] if row else "<not ranked>"

run = one("SELECT status FROM horizon_ranking.ranking_runs WHERE ranking_run_id = %s")[0]
pointer = one("SELECT run_id = %s FROM horizon_api.publications WHERE domain = 'ranking'")
_expect(problems, run == "published" and bool(pointer and pointer[0]),
"the run is published and the ranking publication points at it")
counts = one("""SELECT count(*) FILTER (WHERE role = 'engineer'), count(*) FILTER (WHERE role = 'tech_lead'),
count(*) FILTER (WHERE display_name = 'Rae Quist' OR project_pk = 'p-old')
FROM horizon_ranking.ranked_members WHERE ranking_run_id = %s""")
_expect(problems, counts == (13, 4, 0), "13 engineers and 4 tech leads ranked; the PM and archived project are not")
leads = one("""SELECT count(DISTINCT comparison_group) FROM horizon_ranking.ranked_members
WHERE ranking_run_id = %s AND role = 'tech_lead'""")[0]
_expect(problems, leads == 1, "tech leads share one club-wide comparison group")
_expect(problems, status("Jade Wu") == "group_too_small", "Comet's only engineer is group_too_small")
_expect(problems, status("Milo Grant") == "insufficient_data"
and reason("Milo Grant", "files_majority_owned") == "no_resolved_git_identity",
"Milo Grant (no Git activity) is insufficient_data with no_resolved_git_identity")
_expect(problems, reason("Kai Lee", "verified_completion") == "no_sow"
and reason("Quinn Ash", "team_verified_completion") == "no_sow",
"Dune (no SOW) has delivery NULL with reason no_sow")
beacon = one("""SELECT count(*) FROM horizon_ranking.metric_values
WHERE ranking_run_id = %s AND project_pk = 'p-beacon' AND bucket_key = 'review_collaboration'""")[0]
documents = connection.execute(
"""SELECT document FROM horizon_api.ranking_member_detail
WHERE ranking_run_id = %s AND project_pk = 'p-beacon'""", (run_id,)).fetchall()
weights_ok = documents and all(
"review_collaboration" not in {b["key"] for b in d["buckets"]}
and abs(sum(b["weight"] for b in d["buckets"]) - 1) < 1e-9 for (d,) in documents)
_expect(problems, beacon == 0 and bool(weights_ok),
"Beacon (reviews off) has no review rows and its bucket weights still sum to 1")
unscored = one("""SELECT count(*) FROM horizon_ranking.member_scores
WHERE ranking_run_id = %s AND explanation IS NULL""")[0]
_expect(problems, unscored == 0, "every member has an explanation (Claude or fallback)")
surveys = one("""SELECT count(*) FROM horizon_ranking.metric_values
WHERE ranking_run_id = %s AND bucket_key IN ('peer_ratings', 'leadership_ratings')""")[0]
_expect(problems, surveys == 0, "rubric v2 writes no survey metric rows")
return problems + verify_values(postgres, run_id)


def verify_values(postgres: PostgresResource, run_id: str) -> list[str]:
"""Compare the run's metric values with the ones seed.py worked out itself."""

with postgres.connect() as connection:
rows = connection.execute(
"""SELECT e.metric_key, count(*), count(*) FILTER (WHERE v.raw_value IS NULL
OR abs(v.raw_value - e.value) > 1e-9),
min(m.display_name || ': got ' || coalesce(round(v.raw_value::numeric, 4)::text, 'NULL')
|| ', expected ' || round(e.value::numeric, 4))
FILTER (WHERE v.raw_value IS NULL OR abs(v.raw_value - e.value) > 1e-9)
FROM public.t4_expected e
JOIN horizon_ranking.metric_values v ON v.ranking_run_id = %s
AND v.authentik_user_pk = e.authentik_user_pk AND v.project_pk = e.project_pk
AND v.metric_key = e.metric_key
JOIN horizon_ranking.ranked_members m ON m.ranking_run_id = v.ranking_run_id
AND m.authentik_user_pk = v.authentik_user_pk AND m.project_pk = v.project_pk
GROUP BY 1 ORDER BY 1""", (run_id,)).fetchall()
problems = []
for metric, compared, wrong, example in rows:
_expect(problems, wrong == 0, f"{metric}: {compared - wrong}/{compared} values match seed.py"
+ (f" (e.g. {example})" if example else ""))
return problems


def verify_values_only(postgres: PostgresResource, run_id: str, prefixes: tuple[str, ...]) -> list[str]:
"""verify_values, failing only on metrics with these prefixes (the rest were checked on v2)."""

return [problem for problem in verify_values(postgres, run_id) if problem.startswith(prefixes)]


def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--compare-v1", action="store_true")
args = parser.parse_args()
postgres = PostgresResource(database_url=os.environ["HORIZON_DATABASE_URL"])
settings = get_pipeline_settings()
print("Explanations: " + (f"Claude ({settings.anthropic_model})" if settings.anthropic_api_key
else "no ANTHROPIC_API_KEY, deterministic fallbacks"))
v2 = run(postgres, "v2", FULL)
report(postgres, v2)
problems = verify(postgres, v2)
if args.compare_v1:
v1 = run(postgres, "v1", THROUGH_SCORES)
print("\n== Survey ratings in the v1 run (only the card's respondents count)")
problems += verify_values_only(postgres, v1, ("eng_", "lead_"))
out = Path(__file__).parent / "out"
admin.main(["compare", "--base", v1, "--candidate", v2, "--out", str(out)])
if problems:
print(f"\n{len(problems)} expected result(s) did not hold.")
raise SystemExit(1)
print("\nAll expected results hold.")


if __name__ == "__main__":
main()
Loading
Loading