Skip to content

TaskBuffer and JediTaskBuffer integration - #877

Merged
tmaeno merged 25 commits into
PanDAWMS:masterfrom
tmaeno:master
Nov 19, 2026
Merged

tmaeno merged 25 commits into
PanDAWMS:masterfrom
tmaeno:master

Conversation

@tmaeno

@tmaeno tmaeno commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

This pull request introduces several improvements and bug fixes across the codebase, primarily focusing on more robust handling of task updates and API input validation. The most significant changes are grouped below by theme.

Task update behavior and consistency:

  • The updateTask_JEDI method is now consistently called with updateDEFT=False in multiple modules (AtlasAnalWatchDog.py, AtlasProdWatchDog.py, AtlasWorkflowManagerWatchDog.py, JobGenerator.py, PostProcessor.py, TaskCommando.py, and TaskRefiner.py), ensuring that updates do not propagate to DEFT unless explicitly needed. This change reduces side effects and potential issues when updating task metadata. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14]

API input validation and error handling:

  • The update_event_ranges endpoint now validates that the event_ranges argument is a JSON-encoded list, returning a clear error message if not, and ensures the correct type is passed to the backend. It also serializes the response as JSON when required for legacy clients. [1] [2]
  • The get_status endpoint now directly calls check_job_statuses with a list of job IDs, rather than converting to a comma-separated string, improving clarity and efficiency.

Decorator and type hint improvements:

  • The request_validation decorator in common.py now uses more precise type hints for the task_buffer argument (accepting a callable or an instance), and explicitly checks for missing task_buffer when task_owner checks are requested, returning a clear error response if misconfigured. [1] [2] [3] [4]

Job generation and dataset fetch robustness:

  • Improved error handling and comments in JobGenerator.py for bulk and single dataset fetches, ensuring that failed fetches are handled gracefully and that the logic is clearer for future maintainers. [1] [2] [3] [4]

Miscellaneous fixes:

  • The SchemaChecker.py now uses the correct method to fetch the database version, fixing a potential bug in schema version retrieval.

These changes collectively improve the reliability, maintainability, and clarity of the codebase.

tmaeno and others added 25 commits November 19, 2026 12:01
… error

resetFileStatusInJEDI returns (False, None, None, "database error") when the
database fails. The error is reported, but with --reproduceParent the loop
then iterates the missing map of lost input files and raises TypeError, so
the request ends in an exception instead of the reported failure.
Its result is a dict of workers per harvester, but the error path returned
an empty list, so the declared type was a list-or-dict union that the one
caller (worker_synchronization) indexes by harvester ID. An empty dict
iterates the same way as the empty list did.
request_validation(task_owner=True) checks ownership through task_buffer.
Without one the check raised AttributeError on every request to the
endpoint. Report it as a refused request with a logged error instead. All
four current task_owner endpoints pass a task buffer, so none of them
changes.
Daemon scripts' main(tbuf=...), daemons/utils.py's runner parameters, the
daemon threads and helpers, RecoverLostFilesCore.main, TaskBufferInterface,
request_validation's task_buffer and asyncprocess's TaskBufferLike took the
task buffer as Any. They now say TaskBuffer, imported under TYPE_CHECKING so
that the run-time imports stay inside the functions.

TaskBufferInterfaceChild gets the TYPE_CHECKING base JediTaskBufferInterface
already has (TaskBuffer to a reader, Any to mypy), so the proxy a daemon is
handed instead of a TaskBuffer is accepted where TaskBuffer is declared.
The same holds for JEDI's proxy, so TaskBufferLike no longer needs Any.

Declarations the newly checked calls showed to be narrower than the code:
- resetFileStatusInJEDI takes dn=None: it matches no task owner, so only a
  production manager gets through, which RecoverLostFilesCore relies on
  when run without a userName.
- commandToHarvester's params may be a list: worker_synchronization passes
  the worker IDs, and the body stores whatever it gets as JSON.
- TaskBufferInterface.taskBuffer is installed by launch(), like the process
  and shared objects stop() uses, so it is no longer set to None first.

Also: processor.run binds the default task buffer under its own name so
mypy sees tbuf narrowed, cache_schedconfig passes {} for no bind variables,
and add_main calls cleanup() in a loop instead of a list comprehension.

The declarations were drafted by the code map, which now places the calls
on these receivers.
DBProxy had querySQL(sql) with no bind variables next to querySQLS(sql,
varMap). TaskBuffer.querySQL and JediTaskBuffer.querySQL are a different
method under the same name: they return querySQLS(...)[1]. The only
callers of DBProxy's own querySQL were the two SchemaChecker scripts,
which now call querySQLS(sql, {})[1].

This clears the name for TaskBuffer, which is about to take DBProxy's API
as its type-level base.
DBProxy.cleanup closes one connection. TaskBuffer.cleanup closes a whole pool
of them. They share a name but are different operations on different objects.
The connection-level one is now disconnect(), the counterpart of connect().
Its callers are the pool, ConBridge's child on exit, and the db_read handler.

ConBridge forwards any public DBProxy method to its child, so a pool of
bridges reaches disconnect() as it reached cleanup().
TaskBuffer and JediTaskBuffer each had a same-named wrapper around these
DBProxy methods, and the wrapper does more than pass the call through:
- sendCommandTaskPanda and insertTaskParamsPanda read the task command key
  in the calling process. ConBridge may run the DBProxy in a child process,
  where that context is not seen.
- insertTaskParamsPanda also checks for a banned user.
- setScoutJobDataToTasks_JEDI and prepareTasksToBeFinished_JEDI build the
  site mapper from the pool before taking a proxy.
- getJobs adds the secrets the jobs need.

The DBProxy sides become send_command_task_panda_db, insert_task_params_panda_db,
set_scout_job_data_to_tasks_jedi_db, prepare_tasks_to_be_finished_jedi_db and
get_jobs_db. The wrappers keep the names every caller uses.

Each renamed method's SQL comment now carries its new name, as every DB
proxy method's comment names the method itself. The class prefix is
unchanged. Their log lines and SQL therefore read get_jobs_db and so on
from now on.

The DB-module docstrings that describe insert_task_params_panda_db's own
checks now name it, and so does get_jobs_db's harvester log message.
TaskBuffer.updateEventRanges answers input it cannot decode with the string
json.dumps("ERROR : failed to convert eventRanges with json").
update_event_ranges then read that string as the (Returns, Commands) pair.
The caller got a success whose Returns was '"' and whose Commands was 'E'.

The endpoint now decodes the input first and answers a failure with the
reason when the decode fails.
Four TaskBuffer methods turned what a client sent into what the DBProxy
method takes, under the DBProxy method's own name but with a different
signature. Each had one caller, an api/v1 endpoint. The conversion now
happens in that endpoint, and the TaskBuffer method takes and returns
exactly what the DBProxy method does:
- addMetadata: update_job passes its one job instead of three one-element
  lists.
- checkJobStatus: get_status reads one status per job inside its timed call,
  instead of joining the IDs into a comma list for TaskBuffer to split
  again. Each read now takes its own proxy from the pool.
- updateEventRanges: update_event_ranges decodes the JSON and, for version
  0 clients, encodes the two results as before.
- getJediTasksInTimeRange: get_tasks_modified_since parses since and skips
  an unusable DN. The 30-day cap on how far back to look moves into DBProxy.

Answers to clients are unchanged.
58 parameters across 29 DBProxy methods had no default, while the TaskBuffer
or JediTaskBuffer method that only passed them through did. Callers left
those arguments out and got the wrapper's value. The same defaults are now on
the DBProxy methods, so calling DBProxy directly behaves the same as going
through the wrapper.

Defaults are matched to the DBProxy parameter by position in the delegating
call, not by name. getJobStatisticsPerSiteResource takes timeWindow in
TaskBuffer and time_window in DBProxy.

No default value changes.
- recover_stale_results already had DEFAULT_MAX_ATTEMPTS (3), the
  same as TaskBuffer's 3.
- updateTask_JEDI's updateDEFT is left as it is: JediTaskBuffer
  defaults it to False, DBProxy and TaskBuffer to True. JEDI's callers pass
  it explicitly in the next commit.

The mutable defaults ({}, [], set()) come over from JediTaskBuffer as they
were. The DBProxy methods only read them.
JediTaskBuffer.updateTask_JEDI defaults updateDEFT to False, while TaskBuffer
and DBProxy default it to True. 15 JEDI calls left it out and so ran with
False. They now say False explicitly, so the value no longer depends on
which class answers the call.

The five JEDI calls that already passed False, and the two in
PostProcessorBase that pass True, are unchanged.
on_all_inputs_done clears the task's workflowHoldup flag with updateTask_JEDI
and leaves its status alone. Run from JEDI (AtlasWorkflowManagerWatchDog)
that call had updateDEFT=False, JediTaskBuffer's default. Run from the
server's workflow API it had TaskBuffer's default, True. That rewrote the
DEFT task status to the same value and counted the task's finished jobs to
do it.

It now passes updateDEFT=False on both routes. With False, the status is
still written to DEFT for running, broken, assigning, scouting, aborted,
aborting, exhausted and staging, but not for pending, the usual status of a
held task here.
A failed bulk fetch returns (None, None, None, siteDsMap, parallelOutMap).
The empty chunk already sends that site's jobs to fetch their own output
files one by one. But first the loop over the datasets to register iterated
the None and raised TypeError, so the whole task failed this cycle instead.
The loop is now skipped when there is nothing to register.
The JediTaskBuffer wrapper declared tuple[Any, Any, Any, Any, Any], which
hid what JobGenerator does with the result:
- A failed fetch returns None for the files and the datasets to register.
- A single fetch returns the files as one map; a bulk fetch returns a list of
  maps.

The wrapper now declares DBProxy's type. The callers say what they rely on:
- the per-job fetch takes the datasets to register under their own name and
  keeps the existing None check on the files;
- doGeneratePrePro's failure check also covers a result that is not one map,
  and a missing dataset list.

DBProxy.getOutputFiles_JEDI now turns a missing siteDsMap and parallelOutMap
into empty maps before its try block, not inside it, so the failure return
also hands back a map. Its fourth element is declared dict accordingly.

This is the last mismatch that deleting the delegations would have exposed.
Measured by applying the planned TaskBuffer base to a copy of the tree.
getOutputFiles_JEDI records in siteDsMap the IDs of the template datasets it
instantiates, and in parallelOutMap the file specs it makes, inside its
transaction. On failure the transaction was rolled back, but both maps came
back with those entries in them.

A caller in the same process (JediTaskBuffer used directly) also had its own
siteDsMap changed in place.

9b38b60 made a failed bulk fetch fall back to per-job fetches. That
fallback, and the bulk fetches for the remaining sites, then took a
rolled-back dataset ID as an existing concrete premerged dataset. Before,
the cycle stopped on a TypeError, so the map was never reused.

The method now works on copies of both maps. It returns the copies on
success and the caller's maps, untouched, on failure. Every caller takes
siteDsMap from the return value, so a success reads as before.

Reported in review of 9b38b60.
TaskBuffer and JediTaskBuffer passed most calls straight through to DBProxy,
one hand-copied method at a time: 235 in TaskBuffer and 144 in JediTaskBuffer,
each a `with self.proxyPool.get() as proxy: return proxy.<same name>(...)`.
The copies had drifted from DBProxy. 23 of them dropped a parameter or
renamed one, and none of that was checked.

Those 379 methods are gone.
- For a type checker, TaskBuffer now has DBProxy as its base (under
  TYPE_CHECKING), so tb.X(...) is checked against DBProxy.X itself.
- At run time TaskBuffer.__getattr__ forwards a public DBProxy method
  through the pool, taking a proxy for the call as each copy did. It uses
  ConBridge's rule: a name not starting with "_" that is a method of the
  DBProxy class.
- It is hidden from type checkers, so a misspelt name is still reported. It
  looks the name up on the class, not the instance, so proxyPool read before
  init() is an AttributeError, not a recursion.
- JEDI's pipe receiver and the server's TaskBufferInterface find methods by
  name with hasattr/getattr, and still do.

TaskBuffer keeps a method of its own wherever it does more than pass the
call on. set_workload_metrics only passed DBProxy's own default use_commit=
True, so it goes too.

Checked:
- every deleted name is a forwardable method of the DBProxy class at run
  time;
- the names used on task-buffer receivers across the tree resolve exactly
  as on master;
- mypy is clean.
The forwarding has its own tests.
After the forwarding, JediTaskBuffer still had six methods besides its
constructor:
- querySQL, identical to TaskBuffer's;
- five that do more than one DBProxy call: getDatasetsWithJediTaskID_JEDI,
  checkWaitingTaskPrio_JEDI, setScoutJobDataToTasks_JEDI,
  prepareTasksToBeFinished_JEDI and getUserJobsetID_JEDI.

The five move to TaskBuffer unchanged, and the copy of querySQL goes. The
whole task-buffer API is now TaskBuffer's.

JediTaskBuffer keeps only what is JEDI's:
- it answers JediTaskBufferInterface's commands over the pipe;
- it connects with the JEDI database settings through JEDI's proxy pool.

The five moved methods' annotation-only types are imported under
TYPE_CHECKING in TaskBuffer.

Names used on task-buffer receivers across the tree resolve exactly as on
master. The five still resolve on a JediTaskBuffer, now through
TaskBuffer.
get_data_carousel_requests_by_task_status_JEDI and
get_data_carousel_staging_requests_JEDI return None when the database query
fails. Five watchdog methods unpacked or iterated that None:
keep_alive_ddm_rules, resume_tasks_from_staging, clean_up_requests,
rescue_pending_tasks_with_done_requests and check_staging_requests. The
TypeError ended up in the watchdog's catch-all with a traceback.

check_staging_requests already logged the failure and then iterated anyway.
Since the watchdog calls it before resume_tasks_from_staging in the same try
block, its TypeError also skipped resuming tasks that cycle.

Each method now logs the failed query and returns, the way
check_staging_requests already meant to.
cancel_request is declared bool | None, "True for success, None otherwise",
but returned the database's raw count instead. That was 1 when cancelled,
0 when the request had already ended, and None on failure. It now maps the
count the way retire_request already does.

No caller tells 0 and None apart: the Data Carousel methods ignore the
result, and the one test script only prints it.
…itted

resubmit_request is declared to return the resubmitted request or None, with
a message. When the database answered that the request was not found or not
resubmittable, it returned that False instead. Both callers,
data_carousel_ops and a test script, test the result's truth, so None reads
the same to them.
DataCarouselInterface took its task buffer as Any, so its 42 calls of 21
methods, all of Data Carousel's database access, were checked by nothing
and could not be followed by the code map.

It now says TaskBuffer, imported under TYPE_CHECKING: TaskBuffer imports
this module at run time.
- The server passes a TaskBuffer.
- JEDI passes its JediTaskBufferInterface proxy. That is accepted where
  TaskBuffer is declared, through its TYPE_CHECKING base, so nothing in
  pandaserver names pandajedi.
- getTaskParamsWithID_JEDI, which only JediTaskBuffer used to have, now
  reaches DBProxy through TaskBuffer's forwarding.

The real defects the newly checked calls showed were fixed in the three
commits before this one. The rest are declarations:
- lockProcess_PANDA's time_limit and clean_up_data_carousel_requests_JEDI's
  time_limit_days are float. Their bodies pass them to timedelta, and Data
  Carousel passes fractions (lock_expiration_sec / 60).
- resubmit_data_carousel_request_JEDI returns the spec, False or None, never
  True.
- _get_task_params_map says no task params instead of passing None to
  json.loads and logging the TypeError.
- Results of different kinds no longer share one variable:
  - the requests found by ID;
  - the updated spec;
  - the count of deleted requests;
  - whether staged files were updated.
- The staged-files map passed to updateInputFilesStaged_JEDI is typed.

Requested by the code map, which can now place those calls.
a4d3a43 deleted TaskBuffer's pure delegations and put __getattr__, which forwards
the DB proxy's public methods through the pool, under `if not TYPE_CHECKING:`. The
test still read only the functions at the top level of TaskBuffer's class body, so
35 workflow calls and the three named methods failed (38 failures), though each
resolves at runtime.

The test now builds the set of names TaskBuffer serves the way it serves them: the
functions TaskBuffer defines when its body runs (an `if not TYPE_CHECKING:` branch
is taken, an `if TYPE_CHECKING:` one skipped), plus, when one of them is
__getattr__, the public non-property functions of the DB proxy class and its bases.
It still parses the sources only.

Checked against the imported classes: the model and the runtime agree on all 513
forwardable DB proxy methods and all 44 TaskBuffer methods. An unknown name, a
private DB proxy name and a TaskBuffer without __getattr__ still fail the test.
46257df moved the loop over the job IDs of /v1/job/get_status from TaskBuffer into
the endpoint, which then called checkJobStatus once per job. Each call took a proxy
from the pool: it waited in the pool's queue and woke the connection (a ping, and
with ConBridge a round trip to the child) once per job, where TaskBuffer had taken
one proxy for the whole list.

DBProxy.check_job_statuses runs checkJobStatus for each ID on its own proxy, and the
endpoint calls it once under the timeout. A request takes the pool once again, and
with ConBridge the loop now runs in the child in one round trip.
46257df refused event_ranges that are not JSON. A valid JSON value that is not a
list (a number, null, a string, an object) still went to updateEventRanges, which
failed on it, rolled back, logged an error and answered success with Returns
[false]. The endpoint now refuses it as it refuses malformed JSON, before the
database is touched.
@tmaeno
tmaeno merged commit 31f1a14 into PanDAWMS:master Nov 19, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant