How do I rerun a job that failed halfway, without partial files or duplicates?
Write and check each daily summary in a temporary file, rename it into place, and resume a failed job by computing only the days whose final files are missing.
After this lesson, you can restart a month of daily stock summaries after a failed write, keep the finished days and compute only the missing ones.
What goes wrong when a job writes straight to the final file?
A job that stops while writing leaves a half-written file under the final name, so a restart that skips the days with a file also skips the broken day. When the job stops during 9 April, the file 2024-04-09.csv holds only part of its row, and the six files before it are complete.
Each made-up summary holds one day of 1,000 simulated trades in CCC, the first and last prices in dollars per share and the number of trades, with the day’s date as the seed, so a rerun of a day gives the same numbers. The 22 days are the weekdays of April 2024, and the files go to the folder safe_reruns_demo, emptied at the start. characters=40 writes only the first 40 characters of the file and stands in for the stop, and newline="" keeps the CSV’s line endings.
The following box defines the summary and the direct writer, writes six days and stops during 9 April.
import osimport shutilfrom pathlib import Pathimport numpy as npimport pandas as pdout = Path("safe_reruns_demo")shutil.rmtree(out, ignore_errors=True)out.mkdir()days = pd.bdate_range("2024-04-01", "2024-04-30").strftime("%Y-%m-%d")def day_summary(day): prices =410* np.cumprod(1+ np.random.default_rng(int(day.replace("-", ""))).normal(0, 0.0005, 1000))return pd.DataFrame({"day": [day], "first": [prices[0]], "last": [prices[-1]], "trades": [1000]})def write_direct(table, path, characters=None): path.write_text(table.to_csv(index=False)[:characters], newline="")for day in days[:6]: write_direct(day_summary(day), out /f"{day}.csv")write_direct(day_summary("2024-04-09"), out /"2024-04-09.csv", characters=40)print(sorted(path.stem for path in out.glob("*.csv"))[-2:])print((out /"2024-04-09.csv").read_text())
How do I give a file its final name only after a check?
write_safely writes to a temporary file with the ending .tmp, reads it back and compares it with the table, and only then gives it the final name with os.replace, so a stop during the write leaves a temporary file and no final file. Repeating the stop on 9 April leaves six checked CSVs and one temporary file.
pd.testing.assert_frame_equal raises an AssertionError when the two tables differ, with rtol=1e-12 allowing the tiny change of a price written as text and read back. os.replace renames in one step within one folder, so the final name points either to the old complete file or to the new one. A file that faithfully copies a wrong price still passes, and a rename alone does not protect against a power cut.
The following box empties the folder and repeats the job with the safe writer.
def write_safely(table, path, characters=None): temporary = path.with_suffix(".tmp") write_direct(table, temporary, characters) pd.testing.assert_frame_equal(pd.read_csv(temporary), table, check_dtype=False, rtol=1e-12, atol=0) os.replace(temporary, path)for path in out.iterdir(): path.unlink()for day in days[:6]: write_safely(day_summary(day), out /f"{day}.csv")try: write_safely(day_summary("2024-04-09"), out /"2024-04-09.csv", characters=40)exceptAssertionErroras error:print(type(error).__name__)print(len(list(out.glob("*.csv"))), len(list(out.glob("*.tmp"))))
AssertionError
6 1
How do I resume at the missing days?
resume() lists the days without a final file and computes only those, so after the failure it rebuilds the 16 days from 9 April on, and a second call finds nothing to do. Every day then has one checked file.
Skipping a finished day assumes one writer, unchanged inputs and an unchanged calculation, and each day here stands alone. A running total, as in the lesson on chunk boundaries, also needs the previous total, and a changed input means rebuilding every later day that depends on it.
The following box resumes the job twice.
def resume(): missing_days = [day for day in days ifnot (out /f"{day}.csv").exists()]for day in missing_days: write_safely(day_summary(day), out /f"{day}.csv")return missing_daysrebuilt = resume()print(rebuilt[0], len(rebuilt), len(list(out.glob("*.csv"))), len(resume()))
2024-04-09 16 22 0
Your turn
Delete the file of 15 April 2024, run resume(), and print the days it rebuilds and the number of final files. You should see only 15 April and 22.