Skip to content

Health Software Common Practices

HSCP-T-023 · open test

Usage log of an AI system, per patient and per decision

Serves HSCP-G-250, HSCP-G-176 · Recipe: HSCP-R-036

Code under the licence Apache 2.0 · Python 3.10 or later, standard library only, no network access

What the test checks

The artefact is the exported usage log, one JSON object per event (JSON Lines): evenement (sollicitation, decision, non_utilisee), horodatage, cas, professionnel; systeme, version and resultat for a request; resultat, decision (suivie, modifiee, non_suivie), motif and patient_informe for a decision.

The test accepts the log if each event carries its fields; if each decision refers to an earlier request for the same case and the same result, records whether the patient was informed and, when the proposal is not followed, carries its reason; and if no request remains without a decision beyond the chosen delay.

It reports, without rejecting, a non-use without a reason.

Running the test

python3 verifier.py journal.jsonl --date 2026-12-01T09:00 --delai-heures 24

--date sets the time of the check (now by default), --delai-heures the delay beyond which a request without a decision is rejected (24 by default), --json gives the answer in JSON. Exit code: 0 artefact accepted, 1 artefact rejected, 2 incorrect call. Python 3.10 or later, no dependencies.

Examples

  • exemples/valide/: a proposal not followed with its reason, a proposal followed, a non-use with a reason. Accepted.
  • exemples/refuse/: request without a version, refusal without a reason, request left without a decision, decision outside the list without a request, event outside the list. Rejected.

What the test does not say

  • It does not say that the decisions are good or that the reasons are sincere.
  • It does not say that all requests were logged: only the way the product is built guarantees that.
  • It says nothing about the retention of or access rights to the log.

Code

Download the test (zip archive: program, examples, README, licence) (10 KB) · verifier.py

The code and its messages are not translated (French).

#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 les contributeurs des Gestes communs du logiciel de santé
"""HSCP-T-023 : journal d'usage d'un système d'IA, par patient et par décision.

    python3 verifier.py <journal.jsonl> [--date AAAA-MM-JJTHH:MM] [--delai-heures N] [--json]

Lit le journal, un objet JSON par événement (JSON Lines) : evenement (sollicitation, decision, non_utilisee),
horodatage, cas, professionnel ; systeme, version, resultat pour une sollicitation ; resultat, decision (suivie,
modifiee, non_suivie), motif, patient_informe pour une décision.
Refus : ligne illisible ; événement hors liste ; champ obligatoire absent ; horodatage illisible ; décision hors
liste ; décision non suivie sans motif ; décision sans sollicitation antérieure du même cas et du même résultat ;
information du patient non renseignée ; sollicitation sans décision plus vieille que le délai (24 h par défaut).
Note seulement : non-utilisation sans motif.
Il ne dit pas que les décisions sont bonnes ni que toutes les sollicitations ont été journalisées.

Codes de retour : 0 pièce acceptée, 1 pièce refusée, 2 appel incorrect.
Bibliothèque standard seulement, aucun accès réseau.
"""
import argparse
import datetime as dt
import json
import sys

ID = "HSCP-T-023"
CHAMPS = {"sollicitation": ("horodatage", "cas", "professionnel", "systeme", "version", "resultat"),
          "decision": ("horodatage", "cas", "professionnel", "resultat", "decision"),
          "non_utilisee": ("horodatage", "cas", "professionnel")}
DECISIONS = {"suivie", "modifiee", "non_suivie"}


def instant(v):
    try:
        return dt.datetime.fromisoformat(str(v)).replace(tzinfo=None)
    except ValueError:
        return None


def verifier(chemin, maintenant, delai):
    refus, notes, n = [], [], 0
    sollicitations, decides = {}, set()
    for num, ligne in enumerate(open(chemin, encoding="utf-8"), 1):
        if not ligne.strip():
            continue
        try:
            e = json.loads(ligne)
            assert isinstance(e, dict)
        except (ValueError, AssertionError):
            refus.append(f"ligne {num} : objet JSON illisible")
            continue
        n += 1
        t = e.get("evenement")
        if t not in CHAMPS:
            refus.append(f"ligne {num} : événement hors liste")
            continue
        nom = f"ligne {num} ({t}, cas {e.get('cas') or '?'})"
        manque = [c for c in CHAMPS[t] if e.get(c) in (None, "")]
        if manque:
            refus.append(f"{nom} : champ(s) absent(s) : {', '.join(manque)}")
            continue
        h = instant(e["horodatage"])
        if h is None:
            refus.append(f"{nom} : horodatage illisible")
            continue
        cle = (e["cas"], e.get("resultat"))
        if t == "sollicitation":
            sollicitations[cle] = h
        elif t == "decision":
            if e["decision"] not in DECISIONS:
                refus.append(f"{nom} : décision hors liste")
            elif e["decision"] == "non_suivie" and not e.get("motif"):
                refus.append(f"{nom} : proposition non suivie sans motif")
            if cle not in sollicitations or sollicitations[cle] > h:
                refus.append(f"{nom} : décision sans sollicitation antérieure du même cas et du même résultat")
            if not isinstance(e.get("patient_informe"), bool):
                refus.append(f"{nom} : information du patient non renseignée")
            decides.add(cle)
        elif not e.get("motif"):
            notes.append(f"{nom} : non-utilisation sans motif")
    for cle, h in sollicitations.items():
        if cle not in decides and maintenant - h > dt.timedelta(hours=delai):
            refus.append(f"cas {cle[0]}, résultat {cle[1]} : sollicitation sans décision depuis plus de {delai} h")
    if n == 0:
        refus.append("journal vide")
    return refus, notes, n


def main(argv):
    p = argparse.ArgumentParser(prog="verifier.py", description=__doc__.splitlines()[0])
    p.add_argument("journal")
    p.add_argument("--date", default=dt.datetime.now().isoformat(timespec="minutes"))
    p.add_argument("--delai-heures", type=int, default=24)
    p.add_argument("--json", action="store_true")
    try:
        a = p.parse_args(argv)
        maintenant = dt.datetime.fromisoformat(a.date)
    except (SystemExit, ValueError):
        return 2
    try:
        refus, notes, n = verifier(a.journal, maintenant, a.delai_heures)
    except OSError as e:
        print(f"{ID} : pièce illisible : {e}", file=sys.stderr)
        return 2
    if a.json:
        print(json.dumps({"test": ID, "accepte": not refus, "evenements": n, "refus": refus, "notes": notes},
                         ensure_ascii=False, indent=2))
    else:
        print(f"{ID} : {'pièce acceptée' if not refus else 'pièce refusée'} ({n} événement(s))")
        for x in refus:
            print("  refus :", x)
        for x in notes:
            print("  note :", x)
    return 0 if not refus else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Files of the test