EST. 2026 — Notes from real server work SYSADMIN · SECURITY · AI · DIRECTADMIN Issue 01
THE SYSADMIN ALMANAC
Home / Linux / Readable but Fake Data Files and the Hardcoded UTC Hour Trap
Linux

Readable but Fake Data Files and the Hardcoded UTC Hour Trap

by Ton-Or ·6 Dec 2026·11 min read
Readable but Fake Data Files and the Hardcoded UTC Hour Trap

A broken file at least makes itself known because it will not open. A more dangerous file opens with everything in order, but the data inside never actually happened. The detector written to catch it can be just as quietly wrong.

1-minute summary

Symptom / problem
Eight daily files open fine with the right schema, but are replayed data that never really happened.
Who should read
Anyone maintaining a time-series data store who must verify files are real.
Fix in short
Detect them by the signature that every row falls outside the source's working hours. Ask in the source's local time, not hardcoded UTC hours, and assert before computing.
Jump to steps

I was using the time-series archive for dataset A for another analysis when I noticed working days in the results on days when the source was closed. The source for this dataset sends data only Monday through Friday and is closed on weekends, but my results included Saturdays and Sundays with a full day of data. I went back to open the daily files in the archive and found 8 files where every row fell within a period when the source was closed, without a single row during operating hours.

The dataset and provider names in this article are generic names. The file counts, row counts, and proportions are actual figures from my archive. There are two parts to this story. The first is what the fake data looked like. The second is how the first detector I wrote to catch it got things more seriously wrong than the original problem.

Symptoms: every file opens, but working days appear where they should not

There was nothing wrong with any of the 8 files at the file level. They opened normally with a parquet reader, and every column in the schema matched the other files. Jobs that read the archive therefore never stumbled over these files. The only thing wrong was the timing of the rows inside.

8 filesentirely outside operating hours
1,958,275rows in those files
5.75%of the roughly four-month period in use
0 rowswithin actual operating hours

All the files were for Saturdays or Sundays from late May through July 2026. Together they contained nearly two million rows, accounting for 5.75% of the data from 23 March through the end of July that I was using at the time. That was enough to change the conclusions, because downstream jobs reading the archive did not know which days should not exist. If they saw a file, they read it. If they saw data, they counted it as another working day, generated summary bars for every interval on those Saturdays and Sundays, and fed them into further calculations as if they were real.

The first question I needed to answer before discarding anything was whether this was real data whose timestamps had shifted onto non-working days, or data that had never actually happened. If it was the former, the fix was to shift the timestamps back, not discard it. I therefore had to inspect the data itself to find out what it really was.

The signatures of replayed data

When I placed the suspect files after the real data from the preceding Friday, two clear signatures emerged.

First, the first row's value was far from the actual closing value of the previous session. The values in the file then gradually climbed back, finishing almost exactly at that actual closing value. Continuous real data does not behave this way. If the source closes and then reopens, the first value after reopening should be near the last value before closing, rather than starting far away and working its way back.

Second, about 88% of the values in the file also appeared in nearby weekday files. Two days of genuinely new measurements should not have matching values in such a high proportion.

Real data after the source reopens

Continues from the previous close

The first row is near the last value of the previous session, then progresses naturally. Some values may match nearby days, but not nearly the entire file.

Fake files

Starts far away, then climbs back

The first row is far from the actual closing value. Values climb back to finish almost exactly at that close, and 88% of them match nearby weekday files.

Together, these two signatures answered the first question. This was not real data with shifted timestamps. It was old data replayed through the live feed while the source was closed. It belongs to the same family of problems I described in the article about a live feed overwriting clean historical data. That article was about who had permission to write. This one is about how to detect what has already been written.

Measuring the proportion of repeated values takes only a few lines. I use it for confirmation after the time rule has identified suspects, rather than as the primary screening method.

import numpy as np
import pandas as pd

def replay_score(suspect_file: str, neighbour_file: str, col: str = "val_a") -> float:
    """สัดส่วนของค่าในไฟล์ที่สงสัย ที่ไปปรากฏอยู่ในไฟล์วันธรรมดาข้างเคียง"""
    s = pd.read_parquet(suspect_file, columns=[col])[col].to_numpy()
    n = pd.read_parquet(neighbour_file, columns=[col])[col].to_numpy()
    return float(np.isin(s, np.unique(n)).mean())

def opening_gap(suspect_file: str, prev_file: str, col: str = "val_a") -> float:
    """ระยะห่างระหว่างแถวแรกของไฟล์ที่สงสัย กับค่าสุดท้ายจริงของรอบก่อนหน้า"""
    first = pd.read_parquet(suspect_file, columns=[col])[col].iloc[0]
    last = pd.read_parquet(prev_file, columns=[col])[col].iloc[-1]
    return float(abs(first - last))

The first detector: hardcoded UTC hours

Once I knew the fake data fell outside operating hours, the rule seemed straightforward to write. I knew the source closed for the week on Friday night at around 21:00 UTC and reopened on Sunday night at around 22:00 UTC. I wrote the rule exactly that way.

# รุ่นแรก — ผิด ห้ามเอาไปใช้
def closed_v1(ts_us):
    t = pd.to_datetime(ts_us, unit="us", utc=True)
    fri_late  = (t.dayofweek == 4) & (t.hour >= 21)     # ศุกร์ตั้งแต่ 21:00 UTC
    saturday  = (t.dayofweek == 5)
    sun_early = (t.dayofweek == 6) & (t.hour < 22)      # อาทิตย์ก่อน 22:00 UTC
    return np.asarray(fri_late | saturday | sun_early)

When I ran it against the entire archive, the detector reported 3,860 contaminated files. That number should have made me stop and think immediately, because I had seen 8 files myself. I had also put the same rule into the data loader, making it discard matching rows when reading.

The mistake was assuming that closing time was a fixed UTC hour. The source did not close according to UTC. It closed according to the source server's local time, in a zone that observes daylight saving time. The source's working week runs from Monday 00:00 to Saturday 00:00 in that local time. Converted to UTC, the actual Friday close was therefore 20:59 UTC in summer but 21:59 UTC in winter.

ศุกร์ฤดูร้อน: ต้นทางปิด 20:59 UTCข้อมูลจริงไม่มีข้อมูลศุกร์ฤดูหนาว: ต้นทางปิด 21:59 UTCข้อมูลจริงจริง แต่โดนลบไม่มีข้อมูลหาย 6-13 พันแถวต่อศุกร์กฎ hardcode: ศุกร์ >= 21:00 UTC = ปิด19:0020:0021:0022:0023:00กฎ hardcode ธงขึ้น 3,860 ไฟล์ ในนั้นผิด 3,850 ไฟล์กฎตามเวลาท้องถิ่นของต้นทาง ธงขึ้น 10 ไฟล์
คืนวันศุกร์ตามเวลา UTC เส้นแดงคือเส้นตัดที่ผม hardcode ไว้ ฤดูร้อนเส้นนี้ตรงกับเวลาปิดจริงพอดีเลยไม่เห็นปัญหา ฤดูหนาวต้นทางยังส่งข้อมูลจริงต่ออีกเกือบชั่วโมง ช่วงสีแดงคือข้อมูลจริงที่กฎรุ่นแรกลบทิ้งทุกศุกร์

As a result, every Friday in winter, the entire 21:00 UTC hour contained real data, but my rule said the source was already closed. The loader silently discarded 6,000 to 13,000 real rows every winter Friday. I confirmed this on three winter Fridays: 5 December 2025, 9 January 2026, and 6 March 2026. Hour 21 was missing on all three days.

A faulty detector is more dangerous than no detector

Of the 3,860 files flagged by the first rule, 3,850 were the result of a bug in the rule itself, not fake data. If I had ordered deletion based on that report, I would have lost real data from every winter Friday across the archive. I must always question a detector's numbers before acting on them: do they fit what I have seen myself? Seeing 8 while the detector reports 3,860 is a sign that the detector is wrong, not that the problem is large.

What allowed this bug to hide was the period I tested. The data I was using at the time started in late March 2026, when the 21:00 UTC cutoff happened to match the actual closing time. The wrong rule therefore produced correct results throughout the test period. Not a single real row was lost. Results calculated over that period were unaffected by this bug. But as soon as I ran the same rule against the entire archive going back several years, every winter was affected.

The correct rule: ask in the source's local time

The correct rule is shorter than the wrong one. Instead of converting the closing time to UTC and remembering the number, convert the timestamp to the source's local time, then ask just one question: was it Saturday or Sunday? The timezone database handles daylight saving time entirely on its own.

SOURCE_TZ = settings["SOURCE_TZ"]     # โซนเวลาของแหล่งข้อมูล อ่านจากค่าตั้ง ไม่ hardcode ในโค้ด

def source_closed(ts_us, always_on: bool = False):
    """True ตรงแถวที่อยู่นอกเวลาทำการของต้นทาง
    รอบสัปดาห์ของต้นทาง = จันทร์ 00:00 ถึงเสาร์ 00:00 ตามเวลาท้องถิ่นของมัน"""
    if always_on:                               # ชุดข้อมูลที่ส่งตลอด 24 ชั่วโมง 7 วัน
        return np.zeros(len(ts_us), dtype=bool)
    t = pd.to_datetime(ts_us, unit="us", utc=True).tz_convert(SOURCE_TZ)
    return np.asarray(t.dayofweek >= 5)

Running this rule against the entire archive for dataset A brought the number of flagged files down to exactly 10: the 8 I had seen at the start, plus 2 files from March 2017 that I had never known about.

Item Hardcoded UTC rule Source local-time rule
Files flagged 3,860 10
Actually fake 10 10
False flags 3,850 0
Real data discarded during loading 6,000-13,000 rows per winter Friday 0
Rows outside operating hours across the archive Unreliable 1,958,286 out of 362.8 million (0.54%)
Remember to tell the detector which datasets have no days off

The same archive contains datasets whose sources send data 24 hours a day, 7 days a week. Applying the weekend rule to those datasets would discard all their real data from every weekend. My function therefore also accepts the dataset name, and callers that know which dataset they are reading must always pass it. If they do not, the function assumes a dataset with days off, and that result must not be used for a dataset that sends continuously.

The archive-wide detector: fail-closed, and move rather than delete

The corrected rule needs to live in two places. The first is the data loader, which must discard rows outside operating hours on every read. This must happen at the row level, not by filename, because a single file may contain both real and fake data. The second is a separate archive-wide detector that reports how much contamination each file contains. I designed the second tool around three principles.

Archive-wide detector flowFind archive rootMissing = fail immediately->Read time columnOne file at a time->Count out-of-hours rowsLocal-time rule->Report per fileEntire file or partial->exit 1 if foundQuarantine if requested

First, fail-closed: if the archive directory cannot be found, the detector must fail with a clear message, rather than reporting 0 files checked and 0 problems found. Without care, "nothing was checked" and "checked and clean" produce output that looks the same. Second, the exit code must be nonzero when contaminated files are found, so the detector can serve as a gate before other jobs run. Third, the detector deletes nothing. With --quarantine, it moves files into a quarantine directory beside the archive and prints every move.

# audit_closed_rows.py — ตรวจทั้งคลัง ไม่ลบอะไร ย้ายเฉพาะเมื่อสั่ง
import glob, os, shutil, sys
import numpy as np
import pandas as pd

ROOT = os.environ.get("ARCHIVE_ROOT", "/data/archive")
ALWAYS_ON = {"dataset_f", "dataset_g"}          # ชุดที่ส่งตลอด 24 ชั่วโมง 7 วัน

def datasets():
    if not os.path.isdir(ROOT):
        raise SystemExit(f"FAIL-CLOSED: ไม่พบ root ของคลัง ({ROOT}) "
                         f"ยังไม่ได้ตรวจอะไรเลย ห้ามอ่านผลนี้ว่าสะอาด")
    return [d for d in sorted(os.listdir(ROOT))
            if os.path.isdir(os.path.join(ROOT, d, "raw"))]

def main():
    names = [a for a in sys.argv[1:] if not a.startswith("--")] or datasets()
    quarantine = "--quarantine" in sys.argv
    bad_total = 0
    for name in names:
        if name in ALWAYS_ON:
            print(f"{name:12s} ส่งตลอด 24/7 ไม่ใช้กฎวันหยุด ข้าม")
            continue
        base = os.path.join(ROOT, name, "raw")
        files = sorted(glob.glob(os.path.join(base, "**", "*.parquet"), recursive=True))
        total = closed = 0
        bad = []
        for f in files:
            try:
                ts = pd.read_parquet(f, columns=["time_ts"])["time_ts"].to_numpy(np.int64)
            except Exception as e:
                print(f"  ! อ่านไม่ได้ {os.path.basename(f)}: {e}")
                continue
            if not len(ts):
                continue
            m = source_closed(ts)
            total += len(ts); closed += int(m.sum())
            if m.any():
                bad.append((f, int(m.sum()), len(ts)))
        flag = "   <== CONTAMINATED" if bad else ""
        print(f"{name:12s} {len(files):>6d} files {total:>13,d} rows "
              f"{closed:>10,d} นอกเวลาทำการ ({100 * closed / max(total, 1):.2f}%){flag}")
        for f, c, n in bad:
            print(f"    {os.path.basename(f)[:-8]}  {'ENTIRE FILE' if c == n else f'{c}/{n}'}")
            if quarantine:
                q = os.path.join(ROOT, name, "raw_quarantine")
                os.makedirs(q, exist_ok=True)
                dst = os.path.join(q, os.path.basename(f))
                shutil.move(f, dst)
                print(f"      moved -> {dst}")
        bad_total += len(bad)
    print(f"\n{bad_total} contaminated file(s) found.")
    sys.exit(1 if bad_total else 0)

if __name__ == "__main__":
    main()

The detector's source_closed function is the same one the loader uses, imported from the same place. I do not allow two separate definitions, because the day I fix one and forget the other, the detector and loader will disagree about what they see.

# ผูกเป็นด่านก่อนรันงานวิเคราะห์ — ถ้าคลังยังมีของปลอม งานไม่เริ่ม
python audit_closed_rows.py dataset_a || { echo "[BLOCK] คลังยังมีไฟล์ปนเปื้อน"; exit 1; }

# ย้ายไฟล์ที่ธงขึ้นออกจากทางของตัวอ่าน (ย้าย ไม่ลบ)
python audit_closed_rows.py dataset_a --quarantine

My reason for choosing to move rather than delete comes directly from this experience. The first detector was wrong about 3,850 files. If it had permission to delete them, I would have had no way to recover that data. Moving files makes a detector's mistakes reversible by moving them back. When to delete files in the quarantine directory is a human decision, not the script's.

The final gate: assert before calculating

The shared loader already removes rows outside operating hours, but I have a number of ad hoc scripts that read files directly without going through it. For these, I wrote a guard to call before using an array in calculations. If any rows outside operating hours remain, it must fail immediately and report the count.

def assert_live(ts_us, always_on: bool = False, where: str = ""):
    """ล้มทันทีถ้ายังมีแถวนอกเวลาทำการเหลืออยู่ในอาร์เรย์ที่กำลังจะเอาไปคำนวณ"""
    if always_on:
        return
    n = int(source_closed(ts_us).sum())
    if n:
        raise AssertionError(
            f"ยังมี {n:,} แถวนอกเวลาทำการ{' ใน ' + where if where else ''} "
            f"ให้กรองด้วย ~source_closed(ts) ตอนโหลด หรือรันตัวตรวจทั้งคลังด้วย --quarantine")

# ตัวอย่างการใช้ในสคริปต์เฉพาะกิจ
df = pd.read_parquet("part.parquet")
df = df[~source_closed(df["time_ts"].to_numpy())]
assert_live(df["time_ts"].to_numpy(), where="สคริปต์สรุปรายสัปดาห์")
All results calculated before the fix are invalid

The fake data created entire phantom working days. Every result calculated from the archive before I added the filter is therefore untrustworthy. All historical analyses must be rerun. I listed the jobs that read this archive as work to rerun, and noted that the other datasets in the archive must pass the same detector before I can trust their numbers.

The sequence I now use to audit the archive

  1. Define the source's operating hours in its own local time and let the timezone database convert them. Do not memorize them as UTC hours.
  2. Test the rule on at least one day on each side of a daylight saving time change before running it against the entire archive.
  3. Compare the detector's reported count with what I have seen myself. If they differ by a factor of hundreds, suspect the detector first.
  4. Filter at the row level during loading, rather than excluding files by name.
  5. The archive-wide detector must fail if it cannot find the archive and return a nonzero exit code when it finds contamination.
  6. Have the detector move files into a quarantine directory. Do not give it permission to delete.
  7. Use signatures in the data itself—the first row being far from the actual closing value and the proportion of repeated values—to confirm that flagged files really contain replayed data.
  8. Rerun every analysis that previously read the archive for that period.

In this case, I was caught out twice. The first problem was files that were entirely valid at the file level but contained data that had never actually happened. No schema validator could catch that; it needed knowledge of the source's operating hours. The second was the detector I wrote using that knowledge, but expressed as fixed UTC numbers, which happened to produce correct results over my test period. These days, whenever I see a numeric hour in a code condition related to someone's operating hours, my first questions are whose local time that hour belongs to, and whether they change their clocks twice a year. Anyone using this detector can adjust the timezone and dataset list to match their own sources. If I have left anything out or made a typo, I will come back and fix it later.

Hit something like this? Stuck somewhere?

Come trade notes on the LinuxThai board

→ Continue on the board

Comments 0

No comments yet — be the first