2626from http import HTTPStatus
2727from pathlib import Path
2828from typing import TYPE_CHECKING , Any , Literal
29+ from urllib .parse import urlencode
2930
3031import httpx
3132
3233from ._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+ )
3442from .client import ReportnetClient
3543from .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
3745from .resources .dataflow_ext import DataflowKind
3846
3947if 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
410484def 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 )
0 commit comments