Skip to content
Merged
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
33 changes: 33 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: CI

on:
pull_request:
push:
branches: [main]

permissions:
contents: read

jobs:
checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: astral-sh/setup-uv@v6
with:
python-version: "3.14" # same interpreter the pipeline is developed on

- name: Install locked environment
run: uv sync --locked --extra dev

- name: Tests
run: uv run pytest

- name: Validate project files (same rules as the Claude Code hooks)
run: uv run python scripts/validate_project_files.py

- name: mapping.tsv up to date with the mapping JSON
# TODO: drop the skip once kurmangaliyev_2020 is re-collated (its committed
# mapping.tsv predates the current row order).
run: uv run python scripts/check_mapping_tsv.py --skip kurmangaliyev_2020
46 changes: 46 additions & 0 deletions .github/workflows/fbbt-release-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: FBbt release check

# Weekly: if OLS has a newer FBbt release than the one recorded in
# checks/fbbt_last_checked.json, verify every project's FBbt terms against it
# (current, non-obsolete, label unchanged). On success the record is updated and
# committed; on failure the job fails and the record is left alone, so the next
# run re-checks.

on:
schedule:
- cron: "0 6 * * 1" # Mondays 06:00 UTC
workflow_dispatch:
inputs:
force:
description: "Verify even if the FBbt release is unchanged"
type: boolean
default: false

permissions:
contents: write # to commit the updated record

jobs:
fbbt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: astral-sh/setup-uv@v6
with:
python-version: "3.14"

- name: Install locked environment
run: uv sync --locked

- name: Check for a new FBbt release and verify mappings
id: fbbt
run: uv run python scripts/check_fbbt_release.py ${{ inputs.force && '--force' || '' }}

- name: Commit the updated record
if: steps.fbbt.outputs.updated == 'true'
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add checks/fbbt_last_checked.json
git commit -m "Record verified FBbt release $(jq -r .version checks/fbbt_last_checked.json)"
git push
16 changes: 16 additions & 0 deletions checks/fbbt_last_checked.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"version": "2026-10-01",
"version_iri": "http://purl.obolibrary.org/obo/fbbt/releases/2026-10-01/fbbt.owl",
"checked_at": "2026-10-06",
"source": "https://www.ebi.ac.uk/ols4/api/ontologies/fbbt",
"projects": {
"davie_2018": {
"terms": 64,
"problems": 0
},
"kurmangaliyev_2020": {
"terms": 62,
"problems": 0
}
}
}
18 changes: 18 additions & 0 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,24 @@ machine-readable, carries named types at multiple granularity levels, is the
figures may predate), and yields per-cluster cell counts (`cell_number`) directly.
Either way, mismatches are **flagged for review**, never silently resolved.

## Continuous integration

`.github/workflows/ci.yml` runs on every PR and push to `main` (offline, ~seconds):
`pytest`; `scripts/validate_project_files.py`, which feeds every committed mapping /
type_mapping / term-request / provenance / samples file through the same
`.claude/hooks/check_*.py` validators Claude Code uses on write (hand edits otherwise
bypass them); and `scripts/check_mapping_tsv.py`, which fails if a `mapping.tsv` no
longer matches what `collate_mapping.py` would produce (kurmangaliyev_2020 is skipped
until it is re-collated).

`.github/workflows/fbbt-release-check.yml` runs weekly (and on demand).
`scripts/check_fbbt_release.py` compares OLS's current FBbt release with the one
recorded in `checks/fbbt_last_checked.json` and only when it is newer re-verifies
every project's FBbt terms (current, non-obsolete, label unchanged). On success the
record is updated and committed by the workflow; on failure the job fails and the
record is kept, so the next run re-checks. Not run on PRs: it needs OLS, which is
sometimes unavailable.

## Second project: Davie 2018

`projects/davie_2018/` — Davie et al. 2018, *A Single-Cell Transcriptome Atlas of
Expand Down
100 changes: 100 additions & 0 deletions scripts/check_fbbt_release.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/usr/bin/env python
"""Re-verify all FBbt mappings only when a new FBbt release is out.

Reads the FBbt release last verified from `checks/fbbt_last_checked.json` and asks
OLS for the current FBbt release. If it is the same, exits 0 without checking terms.
If it is new (or nothing is recorded), runs `verify_mappings.verify` for every project
with mappings; when every term is current, non-obsolete and still carries its recorded
label, the record is updated to the new release. If any term fails, the record is NOT
updated (so the next run re-checks) and the exit code is 1.

Usage:
uv run python scripts/check_fbbt_release.py [--force]
Writes `checked=true|false` and `updated=true|false` to $GITHUB_OUTPUT when set.
"""

from __future__ import annotations

import argparse
import datetime as dt
import importlib.util
import json
import os
import sys
import urllib.request
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
RECORD = REPO_ROOT / "checks" / "fbbt_last_checked.json"
OLS_FBBT = "https://www.ebi.ac.uk/ols4/api/ontologies/fbbt"


def current_release() -> dict:
req = urllib.request.Request(OLS_FBBT, headers={"User-Agent": "vfb-scrnaseq/0.0"})
with urllib.request.urlopen(req, timeout=60) as r: # noqa: S310
cfg = json.load(r)["config"]
return {"version": cfg.get("version"), "version_iri": cfg.get("versionIri")}


def _verify_module():
spec = importlib.util.spec_from_file_location(
"verify_mappings", REPO_ROOT / "scripts" / "verify_mappings.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod


def _output(**kv) -> None:
if os.environ.get("GITHUB_OUTPUT"):
with open(os.environ["GITHUB_OUTPUT"], "a") as fh:
fh.writelines(f"{k}={str(v).lower()}\n" for k, v in kv.items())


def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--force", action="store_true", help="verify even if the release is unchanged")
args = ap.parse_args()

record = json.loads(RECORD.read_text()) if RECORD.exists() else {}
rel = current_release()
if not rel["version"]:
print("could not read the current FBbt version from OLS")
return 1
if rel["version"] == record.get("version") and not args.force:
print(f"FBbt {rel['version']} already verified on {record.get('checked_at')}; nothing to do")
_output(checked=False, updated=False)
return 0

print(f"FBbt {rel['version']} (last verified: {record.get('version') or 'never'}) — verifying all mappings")
verify = _verify_module().verify
projects = sorted(p.parent.name for p in (REPO_ROOT / "projects").glob("*/mapping"))
results, failed = {}, False
for project in projects:
terms, problems = verify(project)
results[project] = {"terms": len(terms), "problems": len(problems)}
print(f" {project}: {len(terms)} terms, {len(problems)} problem(s)")
for fid, msg, info in problems:
ex = ", ".join(info["clusters"][:6]) + ("..." if len(info["clusters"]) > 6 else "")
print(f" {fid}: {msg} [used by: {ex}]")
failed |= bool(problems)

if failed:
print("\nSome FBbt terms need attention; record not updated (next run re-checks).")
_output(checked=True, updated=False)
return 1

RECORD.parent.mkdir(exist_ok=True)
RECORD.write_text(json.dumps({
"version": rel["version"],
"version_iri": rel["version_iri"],
"checked_at": dt.date.today().isoformat(),
"source": OLS_FBBT,
"projects": results,
}, indent=2) + "\n")
print(f"\nAll terms OK; recorded FBbt {rel['version']} in {RECORD}")
_output(checked=True, updated=True)
return 0


if __name__ == "__main__":
sys.exit(main())
84 changes: 84 additions & 0 deletions scripts/check_mapping_tsv.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#!/usr/bin/env python
"""Check each project's committed mapping.tsv matches what collate_mapping.py produces.

Catches a mapping JSON (or config / annotations) edited without re-running
`collate_mapping.py`, which would leave the review table stale. Compares parsed rows,
so line endings don't matter. Writes nothing.

Usage:
uv run python scripts/check_mapping_tsv.py [--skip PROJECT ...] # exit 1 if stale
"""

from __future__ import annotations

import argparse
import csv
import importlib.util
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]


def _collate_module():
spec = importlib.util.spec_from_file_location(
"collate_mapping", REPO_ROOT / "scripts" / "collate_mapping.py")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod


def check(project: str, collate) -> list[str]:
"""Return human-readable differences between committed and regenerated rows."""
with (REPO_ROOT / "projects" / project / "mapping.tsv").open() as fh:
reader = csv.DictReader(fh, delimiter="\t")
old_cols, old_rows = reader.fieldnames, list(reader)
cols, rows = collate(project)
new_rows = [{c: str(r.get(c, "")) for c in cols} for r in rows]
diffs = []
if old_cols != cols:
diffs.append(f"columns differ:\n committed {old_cols}\n expected {cols}")
return diffs
old_by = {r["cluster_label"]: r for r in old_rows}
new_by = {r["cluster_label"]: r for r in new_rows}
for lab in sorted(set(old_by) - set(new_by)):
diffs.append(f"{lab}: in mapping.tsv but no longer a cluster")
for lab in sorted(set(new_by) - set(old_by)):
diffs.append(f"{lab}: missing from mapping.tsv")
for lab in sorted(set(old_by) & set(new_by)):
for c in cols:
if old_by[lab][c] != new_by[lab][c]:
diffs.append(f"{lab}: {c} committed {old_by[lab][c]!r} expected {new_by[lab][c]!r}")
if not diffs and [r["cluster_label"] for r in old_rows] != [r["cluster_label"] for r in new_rows]:
diffs.append("row order differs")
return diffs


def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--skip", nargs="*", default=[], help="projects not checked (yet)")
args = ap.parse_args()

collate = _collate_module().collate
projects = sorted(p.parent.name for p in (REPO_ROOT / "projects").glob("*/mapping.tsv"))
stale = {}
for project in projects:
if project in args.skip:
print(f" skip {project}")
continue
diffs = check(project, collate)
print(f" {'STALE' if diffs else 'ok '} {project}")
if diffs:
stale[project] = diffs
for project, diffs in stale.items():
print(f"\n{project}: mapping.tsv is out of date ({len(diffs)} difference(s)); "
f"run: uv run python scripts/collate_mapping.py --project {project}")
for d in diffs[:20]:
print(f" {d}")
if len(diffs) > 20:
print(f" ... {len(diffs) - 20} more")
return 1 if stale else 0


if __name__ == "__main__":
sys.exit(main())
35 changes: 22 additions & 13 deletions scripts/collate_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,12 @@ def _manual_edit_summary(m: dict) -> str:
return f"{me.get('by', '?')}@{me.get('date', '?')}: {me.get('change') or me.get('reason', '')}".strip()


def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--project", required=True)
args = ap.parse_args()
def collate(project: str) -> tuple[list[str], list[dict]]:
"""Return (columns, rows) for a project's mapping.tsv, without writing it."""
cfg = load_config(project)
kind_of = annotation_kind(project, cfg)

cfg = load_config(args.project)
kind_of = annotation_kind(args.project, cfg)

proj = REPO_ROOT / "projects" / args.project
proj = REPO_ROOT / "projects" / project
anns = json.loads((proj / "cell_type_annotations.json").read_text())["annotations"]
prior = _load_prior(proj, cfg)
# extra per-cluster fields from cell_type_annotations.json shown after the label
Expand Down Expand Up @@ -136,12 +133,24 @@ def main() -> None:
rows.sort(key=lambda r: (not r["fbbt_id"], [int(t) if t.isdigit() else t
for t in re.split(r"(\d+)", r["cluster_label"])]))

cols = COLUMNS[:1] + source_cols + COLUMNS[1:]
if prior is not None:
cols = (cols[:cols.index("manual_edit")] + PRIOR_COLUMNS
+ cols[cols.index("manual_edit"):])
return cols, rows


def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--project", required=True)
args = ap.parse_args()

proj = REPO_ROOT / "projects" / args.project
cols, rows = collate(args.project)
out = proj / "mapping.tsv"
with out.open("w", newline="") as fh:
cols = COLUMNS[:1] + source_cols + COLUMNS[1:]
if prior is not None:
cols = (cols[:cols.index("manual_edit")] + PRIOR_COLUMNS
+ cols[cols.index("manual_edit"):])
w = csv.DictWriter(fh, fieldnames=cols, delimiter="\t")
# LF line endings, matching how git stores/checks out the file (no churn)
w = csv.DictWriter(fh, fieldnames=cols, delimiter="\t", lineterminator="\n")
w.writeheader()
w.writerows(rows)
print(f"wrote {len(rows)} rows -> {out}")
Expand Down
Loading
Loading