Skip to content

Commit 7dfd944

Browse files
Merge pull request #8 from eeadata/feat/validate-and-wait-job
validate_and_wait: poll the validation job, fail fast on failed runs
2 parents 2f9104a + 2cb6c69 commit 7dfd944

10 files changed

Lines changed: 415 additions & 69 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,16 @@ release (0.x.y) only fixes bugs. Breaking changes are called out below.
1111
gets a definite warning pointing to `export_to_file()`; a dataflow that answers
1212
`bigData: false` gets no warning, since its tables really are empty. If the lookup
1313
fails or its answer does not say, the old "may be a data lake" warning stays.
14+
- `validate_and_wait` (and `Dataset.validate`) now polls the validation job: the
15+
current backend answers `validation.start_validation` with the job's id, which
16+
that method now returns (`None` on backends that answer an empty body). A job that
17+
ends FAILED, REFUSED or CANCELED raises `JobError` with the job's status and
18+
`info` right away, instead of waiting for the timeout; a finished job with a note
19+
warns with it and stores it in the result's `attrs["validation_note"]`. Without a
20+
job id, or when polling is refused, it waits for the user notification as before,
21+
and now also stops on a refused, canceled or failed notification. New keyword
22+
`provider_id` (the handle passes its own); `start_validation` also takes
23+
`dataflow_id` and `provider_id`.
1424

1525
## 0.1.3 (2026-11-19)
1626

‎docs/reference/easy.md‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -606,24 +606,42 @@ Start a validation, wait until it finishes, return `validation_errors()`.
606606
| `dataset_id` | `int` | yes | | |
607607
| `dataflow_id` | `int` | yes | | |
608608
| `released` | `bool` | no | `False` | |
609+
| `provider_id` | `int \| None` | no | `None` | |
609610
| `timeout` | `float` | no | `600.0` | |
610611
| `poll_interval` | `float` | no | `3.0` | |
611612
| `data_lake` | `bool \| None` | no | `None` | |
612613

613614
**Returns:** `pd.DataFrame`
614615

615616
`data_lake` is passed to `validation_errors()` (None: detect from `bigData`).
616-
617-
WRITES: replaces the dataset's validation results and takes a dataset lock.
618-
The completion signal is the user notification the backend creates when a run
619-
ends (`VALIDATION_FINISHED_EVENT`, or `VALIDATION_RELEASE_FINISHED_EVENT` with
620-
`released=True`), read from `/notification/findUserNotifications`: the dataset
621-
has no status field to poll (live, the sandbox). A run took
622-
about 35-55 s there. Only the calling user's notifications are visible, and a
623-
failed run has no event of its own here, so it ends as a `JobError` timeout.
624-
Notification times are server-side, so a newer one than any seen before the
625-
start counts; a run started by someone else at the same moment could be
626-
mistaken for this one. Raises `JobError` after `timeout` seconds.
617+
`provider_id` goes to the start and the poll; a provider-scoped (reporter)
618+
ApiKey needs it there.
619+
620+
WRITES: replaces the dataset's validation results and takes a dataset lock (a
621+
second start while one runs gets `LockedError`, 423). Runs took about 35-100 s
622+
on the sandbox.
623+
624+
How the end is detected: the current backend answers the start with the
625+
validation job's id, so the job is polled (`pollForJobStatus`, as for imports
626+
and exports). A job that ends FAILED, REFUSED or CANCELED raises `JobError`
627+
with the job's `status` and `info`; a FINISHED job with an `info` text (for
628+
example "There are canceled validation tasks", so the results may be partial)
629+
warns with it and puts it in the result's `attrs["validation_note"]`. Read from the
630+
backend source (`MasterOneVersion` branch); the job polling is not yet tested
631+
live for validations.
632+
633+
Without a job id (older backends), or when the poll route is refused, the
634+
signal is the user notification the backend creates when a run ends
635+
(`VALIDATION_FINISHED_EVENT`, or `VALIDATION_RELEASE_FINISHED_EVENT` with
636+
`released=True`), read from `/notification/findUserNotifications` (live, the
637+
sandbox). A newer refused, canceled or `VALIDATION_FAILED_*` notification
638+
raises `JobError` instead. Only the calling user's notifications are visible,
639+
and their times are server-side, so a newer one than any seen before the start
640+
counts; a run started by someone else at the same moment could be mistaken
641+
for this one.
642+
643+
Raises `JobError` after `timeout` seconds: some backend failures leave the job
644+
running and create no notification.
627645

628646
### validation_errors
629647

‎docs/reference/handles.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ Start a validation, wait for it, return the failures (`easy.validate_and_wait`).
166166
**Returns:** `pd.DataFrame`
167167

168168
Replaces the dataset's validation results and locks the dataset while it runs.
169+
The handle's `provider_id` is passed unless you give one.
169170

170171
### Dataset.validation_errors
171172

‎docs/reference/validation.md‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -204,24 +204,29 @@ queue a validation.
204204
|---|---|---|---|---|
205205
| `dataset_id` | `int` | yes | | |
206206
| `released` | `bool` | no | `False` | |
207+
| `dataflow_id` | `int \| None` | no | `None` | |
208+
| `provider_id` | `int \| None` | no | `None` | |
207209

208-
**Returns:** `None`
210+
**Returns:** `int | None`
209211

210212
**Allowed roles:**
211213

212214
Not stated in the API spec.
213215

214216
The route the Reportnet UI's "Validate" button calls. It only queues an
215-
Orchestrator job and returns None (live, 2026-11-06: the body was a bare
216-
number, `44570`, not understood and not used here). No status is exposed on
217-
a data-lake dataset's listing entry; completion shows as a
218-
`VALIDATION_FINISHED_EVENT` user notification
219-
(`GET /notification/findUserNotifications`), which `easy.validate_and_wait()`
220-
polls. Read the results with `list_group_validations()` (or `_dl()`). This WRITES: it replaces the dataset's
221-
existing validation results and takes a dataset lock (a second start while
222-
one runs may get `423`). Roles: stewards, custodians, lead reporter,
223-
reporter write and similar (see `JobControllerImpl`), or ADMIN. `released`
224-
is for validating a dataset that is being released.
217+
Orchestrator job and returns the job's id (the backend's
218+
`MasterOneVersion` branch answers it as a bare number; live, 2026-11-06,
219+
`44570`), or None when the body is empty (older backends). Poll the id
220+
with `pollForJobStatus` (`easy.validate_and_wait()` does). Completion
221+
also shows as a `VALIDATION_FINISHED_EVENT` user notification
222+
(`GET /notification/findUserNotifications`). Read the results with
223+
`list_group_validations()` (or `_dl()`). This WRITES: it replaces the
224+
dataset's existing validation results and takes a dataset lock (a second
225+
start while one runs gets `423`). Roles: stewards, custodians, lead
226+
reporter, reporter write and similar (see `JobControllerImpl`), or ADMIN.
227+
`dataflow_id` and `provider_id` are optional; on `MasterOneVersion` they
228+
enable the route's ApiKey check (backend source, not tested live).
229+
`released` is for validating a dataset that is being released.
225230

226231
### start_validations_export
227232

‎reportnet_api/easy.py‎

Lines changed: 155 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,22 @@
2626
from http import HTTPStatus
2727
from pathlib import Path
2828
from typing import TYPE_CHECKING, Any, Literal
29+
from urllib.parse import urlencode
2930

3031
import httpx
3132

3233
from ._core import RetryPolicy, atomic_destination, caller_stacklevel
33-
from ._exceptions import ForbiddenError, ReportnetAPIError, _is_rejected_credential_500
34+
from ._exceptions import (
35+
AuthenticationError,
36+
ForbiddenError,
37+
NotFoundError,
38+
ReportnetAPIError,
39+
ServerError,
40+
_is_rejected_credential_500,
41+
)
3442
from .client import ReportnetClient
3543
from .demo import demo_client as _demo_client
36-
from .jobs import JobError, Progress, progress_event, progress_scope
44+
from .jobs import JobError, Progress, progress_event, progress_scope, wait_for_job
3745
from .resources.dataflow_ext import DataflowKind
3846

3947
if TYPE_CHECKING:
@@ -389,22 +397,88 @@ def validation_summary(client: ReportnetClient, dataset_id: int, dataflow_id: in
389397
return grouped[cols]
390398

391399

392-
def _latest_notification_ms(client: ReportnetClient, dataset_id: int, event_type: str) -> int:
393-
"""`insertDate` (ms) of the newest `event_type` user notification for the dataset, or 0.
400+
# Notification event types that end a validation run without results. The
401+
# backend's `MasterDataLakes` and `MasterOneVersion` branches persist these as user
402+
# notifications (`EventType`, `persist=true`); `develop` has none.
403+
_VALIDATION_FAILURE_EVENTS = {
404+
"VALIDATION_REFUSED_EVENT": "REFUSED",
405+
"VALIDATE_AS_PROVIDER_REFUSED_EVENT": "REFUSED",
406+
"VALIDATION_CANCELED_EVENT": "CANCELED",
407+
}
408+
409+
410+
def _validation_failure_status(event_type: str) -> str | None:
411+
"""The job status a failure notification stands for, or None if it is not one."""
412+
if event_type in _VALIDATION_FAILURE_EVENTS:
413+
return _VALIDATION_FAILURE_EVENTS[event_type]
414+
if event_type.startswith("VALIDATION_FAILED_") and event_type.endswith("_EVENT"):
415+
return "FAILED" # e.g. VALIDATION_FAILED_SYSTEM_ERROR_EVENT
416+
return None
417+
418+
419+
def _newest_validation_event(
420+
client: ReportnetClient, dataset_id: int, finished_event: str
421+
) -> tuple[int, str, dict[str, Any]]:
422+
"""Newest `finished_event` or failure notification for the dataset: (ms, type, content).
394423
395424
Reads `GET /notification/findUserNotifications` (hidden route; the list the
396-
Reportnet UI shows, newest first, for the calling user only).
425+
Reportnet UI shows, newest first, for the calling user only). `(0, "", {})` when
426+
there is none.
397427
"""
398428
answer = client.request(
399429
"GET", "/notification/findUserNotifications", params={"pageNum": 0, "pageSize": 50}
400430
).json()
401-
times = [
402-
int(n.get("insertDate") or 0)
403-
for n in (answer or {}).get("userNotifications") or []
404-
if n.get("eventType") == event_type
405-
and (n.get("content") or {}).get("datasetId") == dataset_id
406-
]
407-
return max(times, default=0)
431+
newest: tuple[int, str, dict[str, Any]] = (0, "", {})
432+
for note in (answer or {}).get("userNotifications") or []:
433+
content = note.get("content") or {}
434+
kind = str(note.get("eventType") or "")
435+
if content.get("datasetId") != dataset_id:
436+
continue
437+
if kind != finished_event and _validation_failure_status(kind) is None:
438+
continue
439+
ms = int(note.get("insertDate") or 0)
440+
if ms > newest[0]:
441+
newest = (ms, kind, content)
442+
return newest
443+
444+
445+
def _wait_validation_job(
446+
client: ReportnetClient,
447+
job_id: int,
448+
dataset_id: int,
449+
dataflow_id: int,
450+
provider_id: int | None,
451+
*,
452+
deadline: float,
453+
timeout: float,
454+
poll_interval: float,
455+
) -> dict[str, Any] | None:
456+
"""Poll the validation job until it ends; None when the poll route is refused."""
457+
params: dict[str, int] = {"datasetId": dataset_id, "dataflowId": dataflow_id}
458+
if provider_id is not None:
459+
params["providerId"] = provider_id
460+
url = f"/orchestrator/jobs/pollForJobStatus/{job_id}?{urlencode(params)}"
461+
try:
462+
return wait_for_job(
463+
client,
464+
url,
465+
poll_interval=poll_interval,
466+
timeout=max(0.0, deadline - time.monotonic()),
467+
)
468+
except (AuthenticationError, ForbiddenError, NotFoundError):
469+
# `MasterDataLakes` guards this route with an ApiKey check only.
470+
return None
471+
except ServerError as err:
472+
if _is_rejected_credential_500(err.response_body):
473+
return None # a refused credential, answered as 500 (see `explain`)
474+
raise
475+
except JobError as err:
476+
if err.status is None and "did not finish" in str(err):
477+
raise JobError(
478+
f"Validation job {job_id} for dataset {dataset_id} did not finish within "
479+
f"{timeout:g} seconds (it may still be running on the server)"
480+
) from err
481+
raise
408482

409483

410484
def validate_and_wait(
@@ -413,39 +487,92 @@ def validate_and_wait(
413487
dataflow_id: int,
414488
*,
415489
released: bool = False,
490+
provider_id: int | None = None,
416491
timeout: float = 600.0,
417492
poll_interval: float = 3.0,
418493
data_lake: bool | None = None,
419494
) -> pd.DataFrame:
420495
"""Start a validation, wait until it finishes, return `validation_errors()`.
421496
422497
`data_lake` is passed to `validation_errors()` (None: detect from `bigData`).
423-
424-
WRITES: replaces the dataset's validation results and takes a dataset lock.
425-
The completion signal is the user notification the backend creates when a run
426-
ends (`VALIDATION_FINISHED_EVENT`, or `VALIDATION_RELEASE_FINISHED_EVENT` with
427-
`released=True`), read from `/notification/findUserNotifications`: the dataset
428-
has no status field to poll (live, the sandbox). A run took
429-
about 35-55 s there. Only the calling user's notifications are visible, and a
430-
failed run has no event of its own here, so it ends as a `JobError` timeout.
431-
Notification times are server-side, so a newer one than any seen before the
432-
start counts; a run started by someone else at the same moment could be
433-
mistaken for this one. Raises `JobError` after `timeout` seconds.
498+
`provider_id` goes to the start and the poll; a provider-scoped (reporter)
499+
ApiKey needs it there.
500+
501+
WRITES: replaces the dataset's validation results and takes a dataset lock (a
502+
second start while one runs gets `LockedError`, 423). Runs took about 35-100 s
503+
on the sandbox.
504+
505+
How the end is detected: the current backend answers the start with the
506+
validation job's id, so the job is polled (`pollForJobStatus`, as for imports
507+
and exports). A job that ends FAILED, REFUSED or CANCELED raises `JobError`
508+
with the job's `status` and `info`; a FINISHED job with an `info` text (for
509+
example "There are canceled validation tasks", so the results may be partial)
510+
warns with it and puts it in the result's `attrs["validation_note"]`. Read from the
511+
backend source (`MasterOneVersion` branch); the job polling is not yet tested
512+
live for validations.
513+
514+
Without a job id (older backends), or when the poll route is refused, the
515+
signal is the user notification the backend creates when a run ends
516+
(`VALIDATION_FINISHED_EVENT`, or `VALIDATION_RELEASE_FINISHED_EVENT` with
517+
`released=True`), read from `/notification/findUserNotifications` (live, the
518+
sandbox). A newer refused, canceled or `VALIDATION_FAILED_*` notification
519+
raises `JobError` instead. Only the calling user's notifications are visible,
520+
and their times are server-side, so a newer one than any seen before the start
521+
counts; a run started by someone else at the same moment could be mistaken
522+
for this one.
523+
524+
Raises `JobError` after `timeout` seconds: some backend failures leave the job
525+
running and create no notification.
434526
"""
435527
_require_id(dataset_id, "dataset_id", _DATASET_HINT)
436528
event = "VALIDATION_RELEASE_FINISHED_EVENT" if released else "VALIDATION_FINISHED_EVENT"
437-
baseline = _latest_notification_ms(client, dataset_id, event)
529+
baseline = _newest_validation_event(client, dataset_id, event)[0]
438530
try:
439-
client.validation.start_validation(dataset_id, released=released)
531+
job_id = client.validation.start_validation(
532+
dataset_id, released=released, dataflow_id=dataflow_id, provider_id=provider_id
533+
)
440534
except ForbiddenError as err:
441535
raise _hinted(err, _FORBIDDEN_HINT) from err
442536
deadline = time.monotonic() + timeout
443-
while _latest_notification_ms(client, dataset_id, event) <= baseline:
537+
if job_id is not None:
538+
answer = _wait_validation_job(
539+
client,
540+
job_id,
541+
dataset_id,
542+
dataflow_id,
543+
provider_id,
544+
deadline=deadline,
545+
timeout=timeout,
546+
poll_interval=poll_interval,
547+
)
548+
if answer is not None:
549+
errors = validation_errors(client, dataset_id, dataflow_id, data_lake=data_lake)
550+
if answer.get("info"):
551+
errors.attrs["validation_note"] = str(answer["info"])
552+
warnings.warn(
553+
f"Validation job {job_id} finished with a note: {answer['info']}",
554+
RuntimeWarning,
555+
stacklevel=caller_stacklevel(),
556+
)
557+
return errors
558+
while True:
559+
ms, kind, content = _newest_validation_event(client, dataset_id, event)
560+
if ms > baseline:
561+
status = _validation_failure_status(kind)
562+
if status is None:
563+
break
564+
error = content.get("error")
565+
raise JobError(
566+
f"Validation of dataset {dataset_id} ended with {kind}"
567+
+ (f": {error}" if error else ""),
568+
status=status,
569+
info=str(error) if error else None,
570+
)
444571
if time.monotonic() >= deadline:
445572
raise JobError(
446573
f"No {event} notification for dataset {dataset_id} within {timeout:g} "
447-
"seconds (the validation may still be running, or it failed: a failed "
448-
"run has no event of its own)"
574+
"seconds (the validation may still be running, or it failed without "
575+
"leaving a notification)"
449576
)
450577
time.sleep(poll_interval)
451578
return validation_errors(client, dataset_id, dataflow_id, data_lake=data_lake)

‎reportnet_api/handles.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,9 @@ def validate(self, **kwargs: Any) -> pd.DataFrame:
136136
"""Start a validation, wait for it, return the failures (`easy.validate_and_wait`). WRITES.
137137
138138
Replaces the dataset's validation results and locks the dataset while it runs.
139+
The handle's `provider_id` is passed unless you give one.
139140
"""
141+
kwargs.setdefault("provider_id", self.provider_id)
140142
return easy.validate_and_wait(self.client, self.id, self.dataflow_id, **kwargs)
141143

142144
def export_validations(self, dest: str | os.PathLike[str], **kwargs: Any) -> Path:

0 commit comments

Comments
 (0)