The Live Feed Overwrites Clean Historical Data on Every Reboot
Data repaired and cleaned can become corrupt again on its own if two processes each believe they have the right to write the same day. The question to settle is not how to repair it, but who owns which day.
1-minute summary
- Symptom / problem
- A time-series archive has an hour where values jump and bounce back, identically at every resolution.
- Who should read
- People running a time-series archive with both a live feed and repair jobs.
- Fix in short
- The live feed was overwriting closed days. Make the live writer own today only, and leave repairs of earlier days to a separate job.
I have a time-series store that receives data from a provider through two routes. The first is a live feeder that runs throughout the day. The second is historical archive files that the provider publishes later. One day, I opened a chart for dataset A and found an hour where all the values shifted away from their previous level in a step, then snapped back when the next hour began. Looking back through the same month, I found this on 6 days in total, always at 18:00 UTC. I had to put other work aside to find out how the bad data was getting in, and in the end, what actually needed fixing was not the data but the question of who could write which day.
I have removed the dataset names, provider names, and measured values in this article or replaced them with generic names. The sequence of events, times, and fixes are real. This article accompanies another one about how to detect files that read normally but contain fake data. That one covers detection; this one covers write permissions.
Symptoms: an hour shifts away, then snaps back
My store keeps raw data as timestamped rows, then aggregates it into tables at several intervals, starting at 5 seconds. What I saw was the entire hour at 18:00 UTC stepping upward, staying there for the full hour, then dropping back almost exactly to its original level. This was not a single-row spike like noise, but a whole interval shifting together.
My first suspect was the converter—the step that aggregates raw data into interval tables—because it was the most complex code in the pipeline. I opened the aggregated tables at each level: 5 seconds, 1 minute, 3 minutes, 5 minutes, and 15 minutes. They all showed the same error, in the same hour, by the same amount. This was the first piece of evidence that ruled out the converter, because a bug in aggregation at one interval should affect only that level. Matching errors at every level meant the bad data was already in the raw input before it reached the converter.
My second guess was that the provider itself had sent bad data, in which case there was nothing I could fix. I could test this directly by opening the provider's historical archive file for the same day and hour. The archive was completely smooth, with no step. I also compared it with an independent reference source measuring the same thing. That hour was smooth there too.
The hour at 18:00 UTC is smooth
The file published later by the provider has values continuous with the previous hour, with no upward shift, matching the independent reference.
The same hour shifts as a whole
Data merged by the live feeder during the day shifts away for a full hour, then returns to its original level, with matching errors at every resolution.
So the archive file was clean, my store was dirty, and the only route into the store besides archive files was the live feeder. That left one culprit: the daemon receiving real-time data and merging bad rows into that day's file. I tried converting the affected day again from the archive file and overwriting it. That hour became smooth at every resolution, confirming that both the cause and the repair approach were right.
Repaired, but the clean data can become corrupt again
Once I knew that converting again from archive files fixed it, I wrote a daily repair job to fetch the daily archive files for the latest 3 business days, convert them, and overwrite the data. Stopping there would not have solved it, because while checking what else could write historical days, I found that my own live feeder had an option called --auto-repair that I had been passing in its startup script all along. Its job was to fetch today's and yesterday's data to fill gaps in case the machine had gone down during the day.
The problem was that it fetched from the same live source responsible for the errors. This backfill ran at around 22:15 UTC. The repair job had already overwritten those days with clean data, but when the machine rebooted, the live feeder started with this option, fetched yesterday from the live source, and merged it over the data again. The bad hour came back in full. Put simply, every reboot fetched the bad data again and put it on top of the good data.
This kind of problem is hard to see because both sides are doing exactly what they were written to do. The repair job repairs; the live feeder fills gaps. Neither reports an error. The final contents of the file depend on which runs last, which depends on when the machine reboots.
The live feeder's gap-filling option was designed with good intentions, but it reads from the same source that produces the bad data. Fetching it again fixes nothing. It just reproduces the same bad data and puts it on top of the good data. Before giving any process permission to write historical data, first ask where it reads from.
Restricting writes: the live writer owns today alone
A patch would have been to run the repair job more often, or after every daemon startup. I rejected that approach because it would still let two processes write the same day, merely changing which one wins. I changed the rules instead.
There are two rules. First, the live feeder may write only the day that has not yet closed: today. It must never touch a closed day under any circumstances. Second, historical repair is a separate scheduled job that owns every closed day and must never touch today.
Here, a "day" is not a UTC calendar day but the data's working-day cycle, with a cutoff at 22:00 UTC. I covered the reason for that cutoff and the file layout on disk separately in the article on partitioning a time-series store. All that matters here is that the day number is calculated from the timestamp using integer arithmetic alone, so it can be compared directly in a condition.
# กติกาฝั่งตัวป้อนสด: เขียนได้เฉพาะรอบวันปัจจุบัน
DAY_US = 86_400 * 1_000_000
SHIFT_US = 2 * 3600 * 1_000_000 # ดันเส้นตัด 22:00 UTC ไปชนเที่ยงคืน
def work_day_id(ts_us: int) -> int:
"""เลขประจำรอบวัน นับเป็นจำนวนวันจาก 1970-01-01"""
return (ts_us + SHIFT_US) // DAY_US
def split_live_rows(rows, now_us):
"""คืนเฉพาะแถวของรอบวันปัจจุบัน แถวที่เป็นของวันที่ปิดแล้วไม่เขียน"""
today = work_day_id(now_us)
keep = [r for r in rows if work_day_id(r["ts"]) == today]
dropped = len(rows) - len(keep)
if dropped:
print(f"[WARN] ข้าม {dropped} แถวของวันที่ปิดแล้ว (เป็นหน้าที่ของงานซ่อม)")
return keep
I did not remove the --auto-repair option immediately, because the boot startup script was still passing it. Simply removing the argument would stop the daemon from starting because it would not recognize the option. I handled it in two layers: first, keep accepting the option but do nothing, issue one warning, and continue; second, remove the option from the startup script too.
# ออปชันเก่ายังรับได้ แต่เป็น no-op และเตือนครั้งเดียว
import argparse, warnings
ap = argparse.ArgumentParser()
ap.add_argument("--interval", type=int, default=5)
ap.add_argument("--auto-repair", action="store_true",
help="เลิกใช้แล้ว: การซ่อมย้อนหลังเป็นหน้าที่ของงานตามเวลา")
args = ap.parse_args()
if args.auto_repair:
warnings.warn("--auto-repair ถูกยกเลิก ตัวป้อนสดเขียนเฉพาะวันนี้เท่านั้น "
"วันที่ปิดแล้วให้งานซ่อมรายวันดูแล", DeprecationWarning, stacklevel=1)
The repair job crossed the boundary too
About two weeks after fixing the live feeder, I found that the repair job was breaking the same rule in the opposite direction. The repair job runs at 02:00 UTC, while the source is still sending data for the current daily cycle. Yesterday's daily archive file follows the UTC calendar, from 00:00 to 24:00, but my daily cycle cuts off at 22:00 UTC. That means yesterday's archive file also contains data from 22:00 to 24:00 UTC, and those two hours belong to the current daily cycle, not yesterday's.
The first version of the repair job converted archive files and merged by the day numbers it found. It therefore recreated today's file from just those roughly 2 hours of data, overwriting the file the live feeder had been accumulating since 22:00 UTC. This corrected itself on the live feeder's next pass because it rewrote today, so I did not see permanent corruption. But the system was correct because the timing happened to work out, not because it was designed correctly. If the live feeder were not running at that moment, today's file would be left with just those two hours of data.
The fix was to make the repair job rebuild strictly only daily cycles before the current one, and filter the interval tables to rows belonging to their own day before writing.
# กติกาฝั่งงานซ่อม: สร้างใหม่เฉพาะรอบวันที่ปิดแล้ว ไม่แตะรอบวันปัจจุบัน
def completed_days(day_ids, now_us):
today = work_day_id(now_us)
return sorted(d for d in set(day_ids) if d < today) # < ไม่ใช่ <=
def rebuild_completed(rows_by_day, now_us, write_day):
done = completed_days(rows_by_day.keys(), now_us)
for d in done:
# กรองซ้ำอีกชั้น กันแถวของวันอื่นหลุดเข้ามาจากการสรุปคาบที่คร่อมเส้นตัด
rows = [r for r in rows_by_day[d] if work_day_id(r["ts"]) == d]
write_day(d, rows) # เขียนแบบ temp แล้ว rename ทับ
print(f"rebuilt {len(done)} completed days (today skipped)")
return done
I deliberately included the words today skipped in the final log line every time, because they are evidence that the rule was actually applied on that run, rather than merely existing in the code.
The archive files follow the calendar from 00:00-24:00 UTC, while my store cuts off at 22:00 UTC. A file for "yesterday" therefore always includes two hours of "today." Using the source filename to decide which day to write crosses the boundary every night. The deciding factor must be each row's timestamp, not the downloaded filename.
Scheduling: better to run late than with only 19 minutes to spare
The repair job does not need to be a daemon. It runs once a day after yesterday's archive file is published, so I attached it to the system scheduler rather than leaving it running. The question was what time, which required comparing three sets of times.
| Event | UTC time | Machine time (GMT+7) |
|---|---|---|
| Source closes its daily cycle, during its summer time | 21:00 | 04:00 |
| Source closes its daily cycle, during its winter time | 22:00 | 05:00 |
| Archive file for the day just closed is published | Around 00:41 | Around 07:41 |
| Daily repair job starts | 02:00 | 09:00 |
Archive files lag real time by about a day. Yesterday's file appears at around 00:41 UTC the following day. I scheduled the job for 02:00 UTC, after both the daily close and publication time, leaving more than an hour of margin. Moving it forward to 01:00 UTC to get the data sooner would leave only about 19 minutes after publication. If the source published even a little later than usual, the job would run and find no file. Getting the data an hour earlier was not worth the risk of missing that day's repair, so I noted in the job's documentation that this time must not be moved earlier.
Another easy mistake is that the Windows scheduler uses machine time, not UTC. My machine is set to GMT+7, so the time entered in the task must be 09:00.
# งานซ่อมรายวัน 09:00 เวลาเครื่อง (GMT+7) = 02:00 UTC
schtasks /create /tn "ArchiveDailyRepair" /sc daily /st 09:00 `
/tr "C:\jobs\run_daily_repair.bat"
# สั่งรันมือเวลาอยากทดสอบ ไม่ต้องรอถึงเวลา
schtasks /run /tn "ArchiveDailyRepair"
# ดูผลรอบล่าสุด
Get-Content C:\jobs\logs\daily_repair.log -Tail 20
The source's daily files are about 3 MB per day for dataset A, compared with about 66 MB for a monthly file. Going back 3 business days is therefore very light, taking about 10 seconds per dataset, and the output format matches what the full pipeline produces byte for byte, because the repair job calls the same functions as the full pipeline rather than using a newly written shortcut.
Idempotency and the bug that made a 10-second job reconvert 10 years
The repair job must produce the same result no matter how many times it runs, because I configured it to look back 3 days on every run. That means each day is rebuilt 3 times before leaving the window. If repeated runs produce different results, the system will not be stable. Three conditions make it idempotent. First, read only from archive files, never from data already in the store. Second, replace the day's entire file rather than merging into the existing data. Third, determine the job's scope from the current time using the same formula on every run.
While working on this, I found another related bug worth documenting. The repair job called the full pipeline's source-file discovery function, passing a temporary folder containing only 3 days of files to define its scope. But that function did not use the argument it received. It read a module-level constant instead. As a result, a supposedly limited run gathered all 10 years of source files and converted everything again.
from pathlib import Path
SOURCE_ROOT = Path("/data/raw/zip") # ค่าตั้งต้นของ pipeline เต็ม
# ก่อนแก้: รับ argument มาแต่ไม่ได้ใช้ งานจำกัดขอบเขตเลยไม่เคยจำกัดจริง
def list_source_files_bad(dataset: str, source_root: Path = SOURCE_ROOT):
return sorted((SOURCE_ROOT / dataset).rglob("*.zip"))
# หลังแก้: ใช้ค่าที่ผู้เรียกส่งมาเสมอ
def list_source_files(dataset: str, source_root: Path = SOURCE_ROOT):
return sorted((source_root / dataset).rglob("*.zip"))
This kind of bug does not produce incorrect results. It just turns a job that should finish in 10 seconds into a full-store reconversion, which is impossible to notice unless I look at the runtime. The lesson is that a job claiming to limit its scope must also print how many source files it picked up.
Health checks: detect intervals, not points
Once the repair job existed, I needed a check that it actually worked. I wrote a separate health checker for two things: whether the data was current through the latest day, and whether any bad hours remained. The second required care to avoid false alarms. Defining any jump above a threshold as bad data would flag both genuine rapid movements and single-row spikes. The signature of this problem is not a jump, but a jump away, a sustained offset, then a return to the original level. I therefore counted only intervals lasting at least 3 bars.
import numpy as np
def offset_segments(v: np.ndarray, jump: float, min_len: int = 3):
"""หาช่วงที่ค่ายกตัวออกไปแล้วกลับมาที่ระดับเดิม ยาวอย่างน้อย min_len แท่ง
v = ค่าปิดของแต่ละแท่งเรียงตามเวลา, jump = ขนาดขั้นที่ถือว่าผิดปกติ"""
d = np.diff(v)
steps = np.flatnonzero(np.abs(d) >= jump)
out = []
for a in steps:
base = v[a] # ระดับก่อนยกตัว
for b in steps[steps > a]:
opposite = np.sign(d[b]) == -np.sign(d[a])
back = abs(v[b + 1] - base) < jump / 2 # กลับมาใกล้ระดับเดิม
if opposite and back:
if b - a >= min_len:
out.append((int(a + 1), int(b))) # ดัชนีแท่งแรก-แท่งสุดท้ายของช่วง
break
return out
# ขั้นขึ้น 1 แท่งแล้วไม่กลับ = การเคลื่อนไหวจริง ไม่ถูกธง
# ค่าพุ่งแท่งเดียวแล้วกลับ = ยาวไม่ถึง min_len ไม่ถูกธง
The code above is a shortened version containing only the essentials. The jump value must be set according to the nature of each dataset. I left out my own number because it depends on the data's units. After fixing both sides, I ran this checker against all 5 datasets with a daily close. No bad intervals remained, and all datasets were up to date.
The store also contains 2 other datasets whose sources send data 24 hours a day, 7 days a week, with no daily close. I did not include them in the daily repair job because this bad-hour symptom does not occur in datasets without a daily close. The repair job therefore has only 5 datasets in its default list.
A short procedure for stores with two input routes
- If the errors match at every resolution, do not spend time on the converter. Check the raw data first.
- Compare the suspect interval with the source's archive file and an independent reference to distinguish bad source data from corruption on the way in.
- Identify every process that can write the same day's file, including forgotten gap-filling options.
- Let the live writer own only the current daily cycle, and the repair job own only closed daily cycles. Compare day numbers derived from timestamps, not filenames.
- The repair job reads only archive files, replaces entire days, and produces the same result on repeated runs.
- Schedule it more than an hour after the source's publication time, and remember that the scheduler uses machine time.
- Keep a separate health checker, detect the signature across intervals, and make the repair log report that it skipped today on every run.
I did not stop using the live feeder, because archive files lag by about a day and I still need data during the day. The resulting system repairs itself. The live feeder supplies today's data as it arrives, then once that day closes and its archive file is published, the repair job replaces the entire day with clean data. Data from the live route stays in the store for no more than one day.
I ended up spending more time repairing data than I should have because I treated this as a data quality problem when it was an ownership problem. As long as two processes can write the same day, no number of repairs will settle it. Now, whenever I add a new process that writes to the store, I state at the top of the file which time range it owns and put a day-number check before the line that writes the file. Anyone with a store receiving data through multiple routes is welcome to adapt this approach, adjusting the cutoff and run time to suit their own source. If I have left anything unexplained or made a typo, I will come back and correct it later.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first