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
18 changes: 13 additions & 5 deletions evaluation/cases/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,19 @@ Import is idempotent: running it twice changes nothing the second time. That is
what lets the file be the thing under review — a case arrives as a diff in a
pull request rather than as a row somebody typed into a database.

**Test-IDs are allocated by the backend.** A new case is written without one and
the next export adds it. That asymmetry is deliberate: the Vorlage requires a
number never be reused, including for withdrawn cases, and a hand-written ID is
how one gets reused. `--allow-new-ids` exists only for restoring an exported
file into an empty database.
**Numbers are allocated by the backend.** A new case is written without a
`nummer` and the next export adds it. That asymmetry is deliberate: the Vorlage
requires a number never be reused, including for withdrawn cases, and a
hand-written number is how one gets reused. `--allow-new-ids` exists only for
restoring an exported file into an empty database.

**Labels**: `kategorie`, `testart`, `frageform`, `herkunft`. A label missing
from the file leaves the case's label as it is, so re-importing an older file
does not wipe labels set on screen. See `src/sentra_eval/labels.py`.

**`tag` is a readable label, not the identity.** The export writes each case's
tag. Changing it in the file applies it on the next import and keeps it from
being regenerated; it only has to stay unique.

**`status: freigegeben` approves the case.** The pull request that changed the
file is the review, which is the same act the approve button performs. An
Expand Down
4 changes: 2 additions & 2 deletions evaluation/cases/beispiel.yaml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# The worked example from the Vorlage, section 3. Not part of a real round —
# it is here so the file format has something to read.
#
# A new case is written without a test_id; the backend allocates one and the
# next export writes it back into this file.
# A new case is written without a nummer; the backend allocates one, with a
# tag, and the next export writes both back into this file.

- kategorie: GO
ausgangsfrage: Wie lange darf ein Redner im Plenum sprechen?
Expand Down
221 changes: 173 additions & 48 deletions evaluation/src/sentra_eval/cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@
from sqlalchemy import select
from sqlalchemy.orm import Session, selectinload

from sentra_eval import labels
from sentra_eval.bestand import Bestand
from sentra_eval.categories import Kategorie
from sentra_eval.models import ENTWURF, FREIGEGEBEN, Case, CaseVersion, TestIdSequence
from sentra_eval.models import ENTWURF, FREIGEGEBEN, Case, CaseVersion, Counter

# "TF-GO-014": the prefix, the category abbreviation, a three digit number.
TEST_ID_PATTERN = re.compile(r"TF-(?P<kategorie>[A-Z]{2})-(?P<number>\d{3,})")
# The counter behind every case number. Tag prefixes are counters too, named
# after the prefix, and none of them can be called this.
NUMMER_COUNTER = "nummer"

# A generated tag: a prefix, then its running number, "FI-007".
GENERATED_TAG = re.compile(r"(?P<prefix>.+)-(?P<number>\d{3,})")


class CaseError(RuntimeError):
Expand All @@ -38,43 +42,103 @@ class IncompleteCase(CaseError):


class UnknownCase(CaseError):
"""No case with that Test-ID."""
"""No case with that number."""


class TagTaken(CaseError):
"""Another case already carries this tag."""


# ── Test-ID allocation ──────────────────────────────────────────────
# ── Numbers and tags ────────────────────────────────────────────────


def allocate_test_id(session: Session, kategorie: Kategorie) -> str:
"""The next Test-ID for a category. Never returns the same one twice.
def _counter(session: Session, name: str) -> Counter:
"""The counter row, locked for the rest of the transaction.

The counter row is locked for the duration, so two imports running at once
cannot both read the same next_number. Without the lock this is the classic
read-modify-write race, and the symptom would be a unique-constraint error
on test_id that looks like a bug in the caller.
Locked so two imports running at once cannot both read the same
next_number. Without the lock this is the classic read-modify-write race,
and the symptom would be a unique-constraint error that looks like a bug in
the caller.
"""
row = session.execute(
select(TestIdSequence).where(TestIdSequence.kategorie == kategorie).with_for_update()
select(Counter).where(Counter.name == name).with_for_update()
).scalar_one_or_none()

if row is None:
row = TestIdSequence(kategorie=str(kategorie), next_number=1)
row = Counter(name=name, next_number=1)
session.add(row)
session.flush()
return row


def _take(session: Session, name: str) -> int:
row = _counter(session, name)
number = row.next_number
row.next_number = number + 1
session.flush()
return f"TF-{kategorie}-{number:03d}"
return number


def _reserve(session: Session, name: str, number: int) -> None:
"""Make sure the counter never hands out `number` or anything below it."""
row = _counter(session, name)
row.next_number = max(row.next_number, number + 1)
session.flush()


def allocate_nummer(session: Session) -> int:
"""The next case number. Never returns the same one twice.

A counter rather than max(nummer) + 1, which would hand the number back the
moment the highest case is withdrawn.
"""
return _take(session, NUMMER_COUNTER)


def generate_tag(session: Session, prefix: str) -> str:
"""The next free tag with this prefix, skipping any set by hand."""
while True:
tag = f"{prefix}-{_take(session, prefix):03d}"
if not _tag_in_use(session, tag):
return tag


def _tag_in_use(session: Session, tag: str, *, apart_from: Case | None = None) -> bool:
statement = select(Case.id).where(Case.tag == tag)
if apart_from is not None:
statement = statement.where(Case.id != apart_from.id)
return session.execute(statement).first() is not None


def set_tag(session: Session, case: Case, tag: str) -> Case:
"""Give a case a tag by hand. It is kept from then on, whatever its labels.

An empty tag hands the case back to the generator.
"""
tag = tag.strip()
if not tag:
case.tag = generate_tag(session, labels.tag_prefix(case.kategorie, case.testart))
case.tag_manuell = False
session.flush()
return case
if _tag_in_use(session, tag, apart_from=case):
raise TagTaken(f"Der Tag {tag!r} ist schon vergeben.")
case.tag = tag
case.tag_manuell = True
session.flush()
return case


# ── Writing ─────────────────────────────────────────────────────────


def create_case(
session: Session,
kategorie: Kategorie,
kategorie: str,
ausgangsfrage: str,
*,
testart: str = "",
frageform: str = "",
herkunft: str = "manuell",
abteilung: str = "",
erwartete_antwort: str = "",
referenz_korrekt: str = "",
Expand All @@ -92,7 +156,18 @@ def create_case(
trail could not distinguish "written and approved together" from "approved
without anyone reading it".
"""
case = Case(test_id=allocate_test_id(session, kategorie), kategorie=str(kategorie))
kategorie = labels.normalise_kategorie(str(kategorie))
testart = testart.strip()
case = Case(
nummer=allocate_nummer(session),
tag=generate_tag(session, labels.tag_prefix(kategorie, testart)),
kategorie=kategorie,
testart=testart,
frageform=frageform.strip(),
herkunft=herkunft.strip(),
)
if testart == labels.GRENZFALL_AUSSERHALB:
grenzfall = True
session.add(case)
session.flush()

Expand Down Expand Up @@ -120,7 +195,7 @@ def edit_draft(session: Session, version: CaseVersion, **fields: object) -> Case
"""Change a draft in place. Refuses an approved version."""
if version.is_approved:
raise ApprovedVersionIsImmutable(
f"{version.case.test_id} version {version.version} is approved. "
f"Nr. {version.case.nummer} version {version.version} is approved. "
f"Add a new version instead — an approved version is what runs were measured "
f"against, and editing it would let the expectation follow the answer."
)
Expand Down Expand Up @@ -208,7 +283,7 @@ def approve(
blockers = approval_blockers(version, bestand)
if blockers:
raise IncompleteCase(
f"{version.case.test_id} Version {version.version} kann nicht freigegeben "
f"Nr. {version.case.nummer} Version {version.version} kann nicht freigegeben "
f"werden: {'; '.join(blockers)}."
)

Expand All @@ -219,48 +294,98 @@ def approve(


def seed_case(
session: Session, *, test_id: str, kategorie: Kategorie, **content: object
session: Session,
*,
nummer: int,
tag: str,
kategorie: str,
testart: str = "",
frageform: str = "",
herkunft: str = "",
**content: object,
) -> tuple[Case, CaseVersion]:
"""Create a case at a Test-ID that was allocated elsewhere.
"""Create a case at a number that was allocated elsewhere.

For restoring an exported file into an empty database, and for nothing
else. The counter is advanced past the number so it can never be handed out
again — without that, seeding TF-GO-007 and then creating a case normally
would produce a second TF-GO-007, which is the exact failure the allocator
exists to prevent.
else. The counters are advanced past the number and the tag's running
number, so neither can be handed out again; without that, seeding Nr. 7 and
then creating a case normally would produce a second Nr. 7, which is the
exact failure the counter exists to prevent.

Deliberately not reachable from the API. The import CLI asks for it with an
explicit flag, so it cannot happen as a side effect of a normal import.
"""
match = TEST_ID_PATTERN.fullmatch(test_id)
if match is None or match.group("kategorie") != str(kategorie):
raise CaseError(
f"{test_id!r} is not a Test-ID for category {kategorie}. "
f"Expected the form TF-{kategorie}-001."
)

case = Case(test_id=test_id, kategorie=str(kategorie))
if nummer < 1:
raise CaseError(f"{nummer} is not a case number.")
kategorie = labels.normalise_kategorie(str(kategorie))
tag = tag.strip() or f"{labels.tag_prefix(kategorie, testart)}-{nummer:03d}"
if _tag_in_use(session, tag):
raise TagTaken(f"Der Tag {tag!r} ist schon vergeben.")

case = Case(
nummer=nummer,
tag=tag,
kategorie=kategorie,
testart=testart,
frageform=frageform,
herkunft=herkunft,
)
session.add(case)
session.flush()

number = int(match.group("number"))
row = session.execute(
select(TestIdSequence).where(TestIdSequence.kategorie == kategorie).with_for_update()
).scalar_one_or_none()
if row is None:
row = TestIdSequence(kategorie=str(kategorie), next_number=number + 1)
session.add(row)
else:
row.next_number = max(row.next_number, number + 1)
_reserve(session, NUMMER_COUNTER, nummer)
generated = GENERATED_TAG.fullmatch(tag)
if generated is not None:
_reserve(session, generated.group("prefix"), int(generated.group("number")))

version = CaseVersion(case_id=case.id, version=1, status=ENTWURF, **content)
session.add(version)
session.flush()
return case, version


def set_labels(
session: Session,
case: Case,
*,
kategorie: str | None = None,
testart: str | None = None,
frageform: str | None = None,
herkunft: str | None = None,
) -> Case:
"""Correct a case's labels. Creates no version: labels are not what is measured.

A generated tag follows a new Bereich or Testart; one set by hand stays.
Choosing or leaving the Testart "Grenzfall · außerhalb des Bestands" sets
the grenzfall flag on a draft to match. An approved version keeps its flag:
it is what a round measured against.
"""
before = (case.kategorie, case.testart)
if kategorie is not None:
case.kategorie = labels.normalise_kategorie(kategorie)
if testart is not None:
case.testart = testart.strip()
if frageform is not None:
case.frageform = frageform.strip()
if herkunft is not None:
case.herkunft = herkunft.strip()

if (case.kategorie, case.testart) != before and not case.tag_manuell:
case.tag = generate_tag(session, labels.tag_prefix(case.kategorie, case.testart))

latest = case.versions[-1] if case.versions else None
if testart is not None and latest is not None and not latest.is_approved:
if case.testart == labels.GRENZFALL_AUSSERHALB:
latest.grenzfall = True
elif before[1] == labels.GRENZFALL_AUSSERHALB:
latest.grenzfall = False

session.flush()
return case


def withdraw(session: Session, case: Case) -> Case:
"""Take a case out of future rounds without freeing its Test-ID."""
"""Take a case out of future rounds without freeing its number."""
if case.zurueckgezogen_at is None:
case.zurueckgezogen_at = datetime.now(UTC)
session.flush()
Expand All @@ -271,18 +396,18 @@ def withdraw(session: Session, case: Case) -> Case:


def list_cases(session: Session, *, include_withdrawn: bool = False) -> list[Case]:
statement = select(Case).options(selectinload(Case.versions)).order_by(Case.test_id)
statement = select(Case).options(selectinload(Case.versions)).order_by(Case.nummer)
if not include_withdrawn:
statement = statement.where(Case.zurueckgezogen_at.is_(None))
return list(session.execute(statement).scalars())


def get_case(session: Session, test_id: str) -> Case:
def get_case(session: Session, nummer: int) -> Case:
case = session.execute(
select(Case).options(selectinload(Case.versions)).where(Case.test_id == test_id)
select(Case).options(selectinload(Case.versions)).where(Case.nummer == nummer)
).scalar_one_or_none()
if case is None:
raise UnknownCase(f"No case with Test-ID {test_id!r}.")
raise UnknownCase(f"Kein Testfall mit Nr. {nummer}.")
return case


Expand Down
6 changes: 3 additions & 3 deletions evaluation/src/sentra_eval/categories.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""The categories a test case can belong to.

One definition, because the Test-ID is built from the abbreviation and the
number is allocated per category. Adding a category here is the whole change;
One definition, because a generated tag is built from the abbreviation and
its running number is counted per category. Adding a category here is the whole change;
nothing else holds a copy.

The three the Vorlage names by example are the starting set. It says explicitly
Expand All @@ -19,7 +19,7 @@


class Kategorie(StrEnum):
"""Category abbreviation, as it appears inside a Test-ID."""
"""Category abbreviation, as it appears inside a generated tag."""

GO = "GO" # Geschäftsordnung
GV = "GV" # Gesetzgebungsverfahren
Expand Down
Loading
Loading