fix(import): a malformed row is skipped, not fatal; existence read once per file

Every field a row is read through sits inside the try that turns errors into
skipped, an unknown event kind skips only its run, and persons, templates and
runs are looked up in three queries for the whole file. Report is a dataclass.
The CLI reports a database failure cleanly. "Wyślij do podpisu" is a plain
button: the stage's approval stays the one primary action. Ticket narration
trimmed from comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 14:41:09 +01:00
co-authored by Claude Opus 5.5
parent d429f4e292
commit e2c821e53d
4 changed files with 150 additions and 80 deletions
+1 -1
View File
@@ -90,7 +90,7 @@ backend/app/
requests (types + requests + snapshot) · groups · templates · assignees
runs (start, act) · notify · lists (inbox / mine / archive + CSV, can_* flags)
legacy_import (Galena's old runs + templates as history; `python -m
app.import_galena_runs runs.json [--commit]`, idempotent, Atrium#53)
app.import_galena_runs runs.json [--commit]`, idempotent)
routers/ health auth users admin dashboard (+ GET /stats)
runs (runs, actions, stages, scan, /files upload, /options, inbox/mine/archive, notifications)
templates · requests (fields, types, requests, GET /files/{id}) · groups
+9 -2
View File
@@ -1,11 +1,12 @@
"""One-shot import of Galena's own approval runs and templates (Atrium#53: one approval engine).
"""One-shot import of Galena's own approval runs and templates.
python -m app.import_galena_runs runs.json # dry run: what would be imported
python -m app.import_galena_runs runs.json --commit # import (one transaction)
`runs.json` is Galena's `python -m app.export_workflows --out runs.json`. Idempotent: ids derive from
Galena's, so running it again — or on a later export — adds only what is missing. No `workflow.*`
event, no notification. Exit status 0 = done, 1 = refused (nothing written), 2 = usage.
event, no notification. Rows that cannot be imported are listed as skipped; the rest goes in.
Exit status 0 = done, 1 = refused (nothing written), 2 = usage.
`services/legacy_import.py` says how each row is mapped.
"""
from __future__ import annotations
@@ -17,6 +18,7 @@ import sys
from collections.abc import Sequence
from dredd_core.db import make_engine, make_session_factory
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.pool import NullPool
from .config import get_settings
@@ -47,6 +49,11 @@ def main(argv: Sequence[str] | None = None) -> int:
db.rollback()
print(f"import refused, nothing written: {exc}", file=sys.stderr)
return 1
except SQLAlchemyError as exc:
db.rollback()
print(f"import failed in the database, nothing written: {exc.__class__.__name__}: "
f"{exc}", file=sys.stderr)
return 1
if args.commit:
db.commit()
else:
+137 -74
View File
@@ -5,12 +5,13 @@ Galena drains its old engine (`LEGACY_WORKFLOWS=drain`) and exports its template
* **Templates** become Workflow templates under the rules of THIS module: same stages and keys,
quorum "one" (the old engine had no other), and DEFAULT_SETTINGS for rejection (§5.2a, back a
stage or to the first) — the decision of Atrium#53, so a run started from them now follows it.
stage or to the first), so a run started from them now follows it.
An archived template stays archived. A template naming a person who no longer exists is skipped.
* **Runs** keep what happened: their state, stages, timeline, times and people. Their settings say
`end` for rejection, because under the old engine a rejection ended the run — the history must not
claim a rule it did not run under. Each is on the `DocumentRef` the export pinned (the project's
main file); a run the export could not pin (`subject: null`) is reported, never imported.
* **A bad row is skipped and reported**, never fatal: one malformed run must not hold back the rest.
* **Idempotent.** Every id is derived from the Galena id (uuid5), so a second import of the same file,
or of a later export with more finished runs, adds only what is missing.
* **History, not activity.** No `workflow.*` event (Galena already emitted them when it happened), no
@@ -19,6 +20,7 @@ Galena drains its old engine (`LEGACY_WORKFLOWS=drain`) and exports its template
"""
from __future__ import annotations
import dataclasses
import datetime as dt
import re
import uuid
@@ -38,6 +40,10 @@ FORMAT = "galena-workflows/1"
_NS = uuid.UUID("5f0c1a52-9d36-4f4e-9b0a-6a3f2e3d4c11") # fixed: ids must be the same on every run
_HEX40, _HEX64 = re.compile(r"^[0-9a-f]{40}$"), re.compile(r"^[0-9a-f]{64}$")
_FINISHED = {RunStatus.approved.value, RunStatus.rejected.value, RunStatus.cancelled.value}
_KINDS = {"start": EventKind.start, "zatwierdzenie": EventKind.approval,
"odrzucenie": EventKind.rejection, "anulowanie": EventKind.cancellation,
"zakonczenie": EventKind.finished}
_BAD_ROW = (AppError, KeyError, TypeError, ValueError, AttributeError)
def state_of(state: str, scan: dict | None, stages: list[dict]) -> str:
@@ -47,9 +53,6 @@ def state_of(state: str, scan: dict | None, stages: list[dict]) -> str:
and stages[-1].get("type") == rules.PAPER):
return RunStatus.signed.value
return state
_KINDS = {"start": EventKind.start, "zatwierdzenie": EventKind.approval,
"odrzucenie": EventKind.rejection, "anulowanie": EventKind.cancellation,
"zakonczenie": EventKind.finished}
def new_id(kind: str, galena_id: str) -> uuid.UUID:
@@ -87,62 +90,118 @@ def stage_to(kind: str, stage: int | None, count: int) -> int | None:
return None
@dataclasses.dataclass
class Report:
def __init__(self) -> None:
self.templates = self.runs = self.already = 0
self.skipped: list[str] = []
templates: int = 0
runs: int = 0
already: int = 0
skipped: list[str] = dataclasses.field(default_factory=list)
def _people(db: DbSession, ids: set[str]) -> set[str]:
if not ids:
return set()
found = db.scalars(select(AppUser.id).where(AppUser.id.in_([uuid.UUID(i) for i in ids])))
return {str(i) for i in found}
@dataclasses.dataclass
class _Known:
"""What already exists, read once for the whole file instead of once per row."""
people: set[str]
templates: set[uuid.UUID]
runs: set[uuid.UUID]
def _template(db: DbSession, t: dict[str, Any], report: Report) -> None:
tid = new_id("template", t["id"])
if db.get(WorkflowTemplate, tid) is not None:
report.already += 1
return
def _uuid_or_none(value: Any) -> uuid.UUID | None:
try:
return uuid.UUID(str(value))
except (TypeError, ValueError, AttributeError):
return None
def _why(exc: Exception) -> str:
return str(exc) if isinstance(exc, AppError) else f"malformed ({type(exc).__name__}: {exc})"
def _rows(data: dict[str, Any], key: str, report: Report) -> list[dict[str, Any]]:
rows = data.get(key) or []
if not isinstance(rows, list):
raise ValidationError(f"Not a Galena export: `{key}` is not a list.")
for i, x in enumerate(rows):
if not isinstance(x, dict):
report.skipped.append(f"{key}[{i}]: malformed (not an object)")
return [x for x in rows if isinstance(x, dict)]
def _named_in(stages: Any) -> list[Any]:
out: list[Any] = []
for s in stages if isinstance(stages, list) else []:
a = s.get("approver") if isinstance(s, dict) else None
if isinstance(a, dict) and a.get("kind") == "users" and isinstance(a.get("user_ids"), list):
out.extend(a["user_ids"])
return out
def _known(db: DbSession, templates: list[dict], runs: list[dict]) -> _Known:
ids: list[Any] = []
for t in templates:
ids.extend(_named_in(t.get("stages")))
for r in runs:
ids.append(r.get("started_by"))
ids.extend(e.get("actor_id") for e in (r.get("events") or []) if isinstance(e, dict))
people = {u for u in map(_uuid_or_none, ids) if u is not None}
tids = [new_id("template", str(t.get("id"))) for t in templates]
rids = [new_id("run", str(r.get("id"))) for r in runs]
return _Known(
people={str(i) for i in db.scalars(select(AppUser.id).where(AppUser.id.in_(people)))}
if people else set(),
templates=set(db.scalars(select(WorkflowTemplate.id).where(WorkflowTemplate.id.in_(tids))))
if tids else set(),
runs=set(db.scalars(select(WorkflowRun.id).where(WorkflowRun.id.in_(rids)))) if rids else set())
def _missing(ids: Any, known: _Known) -> bool:
"""True when any id is not a person who exists (an unparseable id raises ValueError)."""
return any(str(uuid.UUID(str(i))) not in known.people for i in ids)
def _template(db: DbSession, t: dict[str, Any], known: _Known, report: Report) -> None:
label = f"template {t.get('id')} ({t.get('name')})"
try:
tid = new_id("template", t["id"])
if tid in known.templates:
report.already += 1
return
stages = stages_of(t["stages"])
name = rules.name(t["name"], "A template's name")
except AppError as exc:
report.skipped.append(f"template {t['id']} ({t.get('name')}): {exc}")
if _missing(_named_in(stages), known):
report.skipped.append(f"{label}: names a person who no longer exists")
return
template = WorkflowTemplate(
id=tid, name=name, stages=stages, archived=bool(t.get("archived")),
settings=rules.merge_settings({"initiator_may_approve": bool(t["initiator_may_approve"])}),
created_at=_when(t.get("created_at")))
except _BAD_ROW as exc:
report.skipped.append(f"{label}: {_why(exc)}")
return
named = {u for s in stages if s["approver"]["kind"] == "users" for u in s["approver"]["user_ids"]}
if named - _people(db, named):
report.skipped.append(f"template {t['id']} ({name}): names a person who no longer exists")
return
template = WorkflowTemplate(
id=tid, name=name, stages=stages, archived=bool(t.get("archived")),
settings=rules.merge_settings({"initiator_may_approve": bool(t["initiator_may_approve"])}),
created_at=_when(t.get("created_at")))
db.add(template)
known.templates.add(tid)
audit.record(db, actor_id=None, action="workflow_template.import", entity_type="workflow_template",
entity_id=tid, detail=f"galena {t['id']}")
report.templates += 1
def _run(db: DbSession, r: dict[str, Any], template_ids: set[uuid.UUID], report: Report) -> None:
rid = new_id("run", r["id"])
if db.get(WorkflowRun, rid) is not None:
report.already += 1
return
label = f"run {r['id']} (document {r['node_id']})"
if r.get("subject") is None:
report.skipped.append(f"{label}: not pinned by the export ({r.get('skipped')})")
return
if r["state"] not in _FINISHED:
report.skipped.append(f"{label}: state {r['state']!r} is not a finished one")
return
events = r.get("events") or []
people = {r["started_by"], *(e["actor_id"] for e in events)}
if people - _people(db, people):
report.skipped.append(f"{label}: a person in its timeline no longer exists")
return
def _run(db: DbSession, r: dict[str, Any], known: _Known, report: Report) -> None:
label = f"run {r.get('id')} (document {r.get('node_id')})"
try:
rid = new_id("run", r["id"])
if rid in known.runs:
report.already += 1
return
if r.get("subject") is None:
report.skipped.append(f"{label}: not pinned by the export ({r.get('skipped')})")
return
if r["state"] not in _FINISHED:
report.skipped.append(f"{label}: state {r['state']!r} is not a finished one")
return
events = r.get("events") or []
if _missing([r["started_by"], *(e["actor_id"] for e in events)], known):
report.skipped.append(f"{label}: a person in its timeline no longer exists")
return
s = r["subject"]
subject = DocumentRef(document_id=s["document_id"], path=s["path"],
commit_sha=s["commit_sha"], sha256=s["sha256"])
@@ -153,34 +212,37 @@ def _run(db: DbSession, r: dict[str, Any], template_ids: set[uuid.UUID], report:
scan = to_dict(DocumentRef(document_id=s["document_id"], path=r["scan"]["path"],
commit_sha=r["scan"]["commit_sha"],
sha256=r["scan"]["sha256"]))
except (AppError, KeyError, TypeError, ValueError) as exc:
report.skipped.append(f"{label}: {exc}")
timeline = []
for e in events:
kind = _KINDS.get(e["kind"])
if kind is None:
raise ValidationError(f"unknown event kind {e['kind']!r}")
timeline.append(WorkflowEvent(
id=new_id("event", e["id"]), run_id=rid, kind=kind.value,
stage_from=None if e["kind"] == "start" else e.get("stage"),
stage_to=stage_to(e["kind"], e.get("stage"), len(stages)), round=1,
actor_id=uuid.UUID(e["actor_id"]), note=e.get("note"),
evidence=evidence_of(e.get("evidence")), created_at=_when(e["created_at"])))
template_id = new_id("template", r["template_id"]) if r.get("template_id") else None
run = WorkflowRun(
id=rid, template_id=template_id if template_id in known.templates else None,
template_name=r["template_name"], stages=stages,
# Under the old engine a rejection ended the run: the history keeps that rule.
settings=rules.merge_settings({
"initiator_may_approve": bool(r["initiator_may_approve"]),
"on_reject_by_owner": "end", "on_reject_by_approver": "end"}),
current=None, state=state_of(r["state"], scan, stages),
started_by=uuid.UUID(r["started_by"]), round=1, scan=scan,
created_at=_when(r.get("created_at")), updated_at=_when(r.get("updated_at")))
run.set_ref(subject)
except _BAD_ROW as exc:
report.skipped.append(f"{label}: {_why(exc)}")
return
template_id = new_id("template", r["template_id"]) if r.get("template_id") else None
run = WorkflowRun(
id=rid, template_id=template_id if template_id in template_ids else None,
template_name=r["template_name"], stages=stages,
# Under the old engine a rejection ended the run: the history keeps that rule.
settings=rules.merge_settings({
"initiator_may_approve": bool(r["initiator_may_approve"]),
"on_reject_by_owner": "end", "on_reject_by_approver": "end"}),
current=None, state=state_of(r["state"], scan, stages),
started_by=uuid.UUID(r["started_by"]), round=1, scan=scan,
created_at=_when(r.get("created_at")), updated_at=_when(r.get("updated_at")))
run.set_ref(subject)
db.add(run)
db.flush() # the run before its timeline: no relationship() orders the INSERTs
for e in events:
kind = _KINDS.get(e["kind"])
if kind is None:
raise ValidationError(f"{label}: unknown event kind {e['kind']!r}.")
db.add(WorkflowEvent(
id=new_id("event", e["id"]), run_id=rid, kind=kind.value,
stage_from=None if e["kind"] == "start" else e.get("stage"),
stage_to=stage_to(e["kind"], e.get("stage"), len(stages)), round=1,
actor_id=uuid.UUID(e["actor_id"]), note=e.get("note"),
evidence=evidence_of(e.get("evidence")), created_at=_when(e["created_at"])))
for event in timeline:
db.add(event)
known.runs.add(rid)
audit.record(db, actor_id=None, action="workflow_run.import", entity_type="workflow_run",
entity_id=rid, detail=f"galena {r['id']}, {r['state']}, {len(events)} events")
report.runs += 1
@@ -191,10 +253,11 @@ def import_export(db: DbSession, data: dict[str, Any]) -> Report:
if not isinstance(data, dict) or data.get("format") != FORMAT:
raise ValidationError(f"Not a Galena export (expected format {FORMAT}).")
report = Report()
for t in data.get("templates") or []:
_template(db, t, report)
templates, runs = _rows(data, "templates", report), _rows(data, "runs", report)
known = _known(db, templates, runs)
for t in templates:
_template(db, t, known, report)
db.flush()
template_ids = set(db.scalars(select(WorkflowTemplate.id)))
for r in data.get("runs") or []:
_run(db, r, template_ids, report)
for r in runs:
_run(db, r, known, report)
return report
+3 -3
View File
@@ -856,7 +856,7 @@ const stepFoot = (label) => `<div class="form-foot"><a class="btn" href="#/new">
/* Nowa sprawa, a document: an upload, or a Galena document by id and path, re-pinned by the server
at start. A Galena role is a stage only a document can have, so the editor offers it only then.
Galena's "Send for approval" (Atrium#53: Galena has no menu entry) opens this screen as
Galena's "Send for approval" opens this screen as
`#/runs/new?kind=document&document_id=…&path=…`: the document arrives chosen and locked, and the
server still re-pins it with the person's token, so the link grants nothing by itself. */
async function viewNewRun(C, q) {
@@ -1007,7 +1007,7 @@ async function viewRun(C, id) {
+ `<div class="run-grid"><div>${subjectCard()}</div><div>${timelineCard()}</div></div>`;
}
/* Handing an approved document to signing (Atrium#53, "przekazanie do Parafy"): Parafa's new request
/* Handing an approved document to signing: Parafa's new request
with the Galena document prefilled AT THE COMMIT THIS RUN APPROVED (`version`), so exactly the approved
bytes are signed. Platform only (Parafa at ../parafa/), an approved run on a Galena PDF only: Parafa
signs PDFs, and a paper ending (`podpisany`) is already signed. */
@@ -1028,7 +1028,7 @@ function runActions() {
const b = (action, primary) => `<button class="btn${primary ? ' primary' : ''}" onclick="openAction('${action}')">${esc(ACTION[action][0])}</button>`;
const out = [];
const sign = signingUrl(r);
if (sign) out.push(`<a class="btn primary" href="${esc(sign)}">${svg(ICN.check)}Wyślij do podpisu</a>`);
if (sign) out.push(`<a class="btn" href="${esc(sign)}">${svg(ICN.check)}Wyślij do podpisu</a>`);
if (mayEditRequest()) out.push(`<button class="btn" onclick="openEditRequest()">Edytuj wniosek</button>`);
if (r.can_add_stage) out.push(`<button class="btn" onclick="guard(openAddStage)">${svg(ICN.plus)}Dodaj etap</button>`);
if (r.can_refresh) out.push(b('refresh'));