1919still going changes its files, the signature moves, the job is parsed again.
2020A cached job that was parsed by an older version of ``parse`` is refreshed
2121too — the signature carries ``parse.SCHEMA`` so a change there invalidates.
22+
23+ A job that has ended (``_ended``: its result records a finish and nothing
24+ running or pending) is checked by its *head* alone: its own result.json and
25+ config.json, and its folder, whose mtime moves when a trial folder comes or
26+ goes. A Harbor resume rewrites result.json, so it is caught; a file changed
27+ inside a trial of an ended job and nothing else is not. The workspace's
28+ Refresh (``clear_cache``) reads every job again. A job a run of this
29+ application writes is checked trial by trial while that run goes on (a host
30+ run's copy can bring a trial's files after the job's own), and its head
31+ carries the run's end, so the last copy is checked trial by trial once more.
2232"""
2333from __future__ import annotations
2434
@@ -311,6 +321,25 @@ def stat(path):
311321 return hashlib .sha256 ("\n " .join (parts ).encode ()).hexdigest (), trials
312322
313323
324+ def _head (job_dir : str ) -> str :
325+ """What an ended job's parse can change by without a trial changing in place:
326+ its own records, and its folder's mtime (a trial folder added or removed)."""
327+ parts = [f"schema={ SCHEMA } /{ parse .SCHEMA } " ]
328+ for path in (job_dir , os .path .join (job_dir , "result.json" ), os .path .join (job_dir , "config.json" )):
329+ try :
330+ st = os .stat (path )
331+ except OSError :
332+ parts .append ("-" )
333+ continue
334+ parts .append (f"{ st .st_size } :{ st .st_mtime_ns } " )
335+ return "\n " .join (parts )
336+
337+
338+ def _ended (job : parse .Job ) -> bool :
339+ """Its result records a finish and nothing running or pending: its trials are final."""
340+ return job .finished_at is not None and job .state == "finished"
341+
342+
314343def _encode (obj ):
315344 if isinstance (obj , datetime ):
316345 return {"$dt" : obj .isoformat ()}
@@ -381,37 +410,70 @@ def _write_index(ws: Workspace, index: dict) -> None:
381410 _write_atomically (_index_path (ws ), lambda fh : json .dump (index , fh , ensure_ascii = False , indent = 1 ))
382411
383412
384- # Jobs already decoded in this process, by cache file: (signature, Job). A page
385- # that loads the workspace then skips the JSON decode and the rebuild of every
386- # unchanged job. A Job is never changed once loaded (parse.split_agents and the
387- # compare page make new ones with dataclasses.replace).
413+ # Jobs already decoded in this process, by cache file: (signature, Job, trial
414+ # signatures, head). A page that loads the workspace then skips the JSON decode
415+ # and the rebuild of every unchanged job. A Job is never changed once loaded
416+ # (parse.split_agents and the compare page make new ones with dataclasses.replace).
388417_DECODED : dict = {}
389418_DECODED_LOCK = threading .Lock ()
390419
391420
392- def load_job (ws : Workspace , job_dir : str , index : dict | None = None ) -> tuple :
393- """(Job, from_cache). Parses only when the signature changed. ``index``:
394- the rail's index as load_jobs holds it, noted in place."""
395- sig , trial_sigs = _signatures (job_dir )
421+ def _read_cache (path : str , job_dir : str ) -> tuple | None :
422+ """(signature, head, Job) of the cache file *path* when it is *job_dir*'s, else None."""
423+ try :
424+ with open (path , encoding = "utf-8" ) as fh :
425+ cached = json .load (fh , object_hook = _decode )
426+ # "agents": a cache from before split_agents knows nothing of a job's several agents
427+ if cached .get ("dir" ) == job_dir and "agents" in cached .get ("job" , {}):
428+ return cached .get ("signature" ), cached .get ("head" ), job_from_dict (cached ["job" ])
429+ except (OSError , json .JSONDecodeError , TypeError , KeyError , ValueError , AttributeError ):
430+ pass
431+ return None
432+
433+
434+ def _write_cache (ws : Workspace , path : str , sig : str , head : str , job : parse .Job ) -> None :
435+ os .makedirs (ws .jobs_dir , exist_ok = True )
436+ _write_atomically (path , lambda fh : json .dump ({"signature" : sig , "head" : head , "dir" : job .dir , "cached" : _now (),
437+ "job" : job_to_dict (job )}, fh , default = _encode , ensure_ascii = False ))
438+
439+
440+ def load_job (ws : Workspace , job_dir : str , index : dict | None = None , runs : dict | None = None ) -> tuple :
441+ """(Job, from_cache). Parses only when the signature changed; an ended job
442+ whose head is unchanged is not stated trial by trial. ``index``: the
443+ rail's index as load_jobs holds it, noted in place. ``runs``: job folder
444+ name -> the end of the run of this application that writes it, None while
445+ that run goes on; a job no run writes has no entry."""
446+ run = (runs or {}).get (os .path .basename (job_dir ), "" )
447+ short = run is not None # the head alone may answer
448+ head = _head (job_dir ) + (f"\n run={ run } " if run else "" ) # before anything is read: a change after it is caught next time
396449 path = _cache_file (ws , job_dir )
397450 with _DECODED_LOCK :
398451 known = _DECODED .get (path )
452+ if short and known is not None and known [1 ].dir == job_dir and known [3 ] == head and _ended (known [1 ]):
453+ _note_in_index (ws , job_dir , known [1 ], index )
454+ return known [1 ], True
455+ cached = _read_cache (path , job_dir ) if known is None else None
456+ if short and cached is not None and cached [1 ] == head and _ended (cached [2 ]):
457+ with _DECODED_LOCK :
458+ _DECODED [path ] = (cached [0 ], cached [2 ], {}, head )
459+ _note_in_index (ws , job_dir , cached [2 ], index )
460+ return cached [2 ], True
461+ sig , trial_sigs = _signatures (job_dir )
399462 if sig :
400463 if known is not None and known [0 ] == sig and known [1 ].dir == job_dir :
464+ with _DECODED_LOCK :
465+ _DECODED [path ] = (sig , known [1 ], known [2 ], head )
401466 _note_in_index (ws , job_dir , known [1 ], index )
402467 return known [1 ], True
403- try :
404- with open (path , encoding = "utf-8" ) as fh :
405- cached = json .load (fh , object_hook = _decode )
406- # "agents": a cache from before split_agents knows nothing of a job's several agents
407- if cached .get ("signature" ) == sig and cached .get ("dir" ) == job_dir and "agents" in cached .get ("job" , {}):
408- job = job_from_dict (cached ["job" ])
409- with _DECODED_LOCK :
410- _DECODED [path ] = (sig , job , trial_sigs )
411- _note_in_index (ws , job_dir , job , index )
412- return job , True
413- except (OSError , json .JSONDecodeError , TypeError , KeyError , ValueError ):
414- pass
468+ if known is not None :
469+ cached = _read_cache (path , job_dir )
470+ if cached is not None and cached [0 ] == sig :
471+ if cached [1 ] != head and _ended (cached [2 ]):
472+ _write_cache (ws , path , sig , head , cached [2 ]) # read by its head from the next process on
473+ with _DECODED_LOCK :
474+ _DECODED [path ] = (sig , cached [2 ], trial_sigs , head )
475+ _note_in_index (ws , job_dir , cached [2 ], index )
476+ return cached [2 ], True
415477 reuse = None
416478 if known is not None and known [1 ].dir == job_dir :
417479 before = {t .dir : t for t in known [1 ].trials }
@@ -420,23 +482,22 @@ def load_job(ws: Workspace, job_dir: str, index: dict | None = None) -> tuple:
420482 reuse = lambda sub : before .get (sub ) if old_sigs .get (sub ) and old_sigs .get (sub ) == trial_sigs .get (sub ) else None
421483 job = parse .parse_job (job_dir , reuse = reuse )
422484 if sig :
423- os .makedirs (ws .jobs_dir , exist_ok = True )
424- _write_atomically (path , lambda fh : json .dump ({"signature" : sig , "dir" : job_dir , "cached" : _now (),
425- "job" : job_to_dict (job )}, fh , default = _encode , ensure_ascii = False ))
485+ _write_cache (ws , path , sig , head , job )
426486 with _DECODED_LOCK :
427- _DECODED [path ] = (sig , job , trial_sigs )
487+ _DECODED [path ] = (sig , job , trial_sigs , head )
428488 _note_in_index (ws , job_dir , job , index )
429489 return job , False
430490
431491
432- def load_jobs (ws : Workspace , roots ) -> list :
492+ def load_jobs (ws : Workspace , roots , runs : dict | None = None ) -> list :
433493 """Every job under *roots*, each from the cache when its files are
434- unchanged. Same order and de-duplication as ``parse.load_all``."""
494+ unchanged. Same order and de-duplication as ``parse.load_all``.
495+ ``runs``: as ``load_job``'s."""
435496 # the rail's index read once and written once, not once per job: re-reading it for
436497 # each made a workspace of n jobs cost n parses of an index of n entries
437498 index = job_index (ws )
438499 before = dict (index )
439- jobs = [load_job (ws , d , index )[0 ] for d in parse .find_job_dirs (roots )]
500+ jobs = [load_job (ws , d , index , runs )[0 ] for d in parse .find_job_dirs (roots )]
440501 if index != before :
441502 _write_index (ws , index )
442503 return parse .split_agents (jobs )
0 commit comments