#!/usr/bin/env python3 """Recount a CreativeRoll report from the days of its delivery ledger. Download one or more days from the Delivery ledger window of a report (the files ledger--.ndjson), run this script on them, and it counts the report's figures again from the lines, by the rules our counters use, per campaign, placement and creative, for each day, with the totals. Nothing is taken on trust from us but the lines themselves, and ledger-check.py shows whether those are the lines that were sealed. Usage: python3 report-check.py ledger-12-2026-10-20.ndjson python3 report-check.py ledger-12-2026-10-19.ndjson ledger-12-2026-10-20.ndjson ledger-12-2026-10-21.ndjson --day 2026-10-20 python3 report-check.py ledger-12-*.ndjson --tz Europe/Bucharest --csv > recount.csv --day YYYY-MM-DD only that day's rows and totals (give it more than once for several days); the other files are read for the events that came late. --tz ZONE group by the agency's own day in that IANA time zone (Europe/Bucharest, Europe/London) instead of the UTC day. Needs Python 3.9 or later (zoneinfo). --campaign ID only that campaign. --csv the rows as CSV, to open in a spreadsheet. How to compare with the report. A ledger day is a UTC day; the report reads the agency's days in its time zone. Either set the report's time zone to UTC, or use the report's table by hour, or give this script --tz with the agency's zone. A local day spans two UTC days, so download both. Events count in the hour their impression was served, as the report counts them: a click at 00:05 on an impression served at 23:58 belongs to the day before, and is in the next day's file. Give the day after too, or the last minutes of a day lack some of their late events (the script says which days it read and which it did not). The rules, as the server counts (CreativeServeController, ServingCounter, RenderLedger, Metrics): Requests every "req" line (each request, served or not, its outcome in "o"), plus each tracker's call: an "imp" line with no served hour ("sh"), counted by a pixel or a script, is a request of its own. Counted in the hour of the line. Served "req" lines whose outcome is Served. Impressions every "imp" line, invalid ones included, in its served hour. Rendered impressions counted by our tag or our VAST ("m" Served or Vast); render rate = rendered / served. Invalid "imp" lines that carry "ivt" (found at serving or told by the page), plus "ivt" lines: an impression our measurement script counted valid that its page then showed to be driven by a program. Valid = impressions - invalid. Signals a "view", "time", "int", "clk", "done", "msg", "msgseen" or "nomeasure" line counts for the valid figures when it has no "ivt"; with "ivt" it is the invalid impression's, kept apart (since 1.26.1 also what came with the beacon that showed it invalid; before, those few lines did not say so). Each line is already counted once: the server keeps only the first viewable, interaction, completion and message of an impression, so the lines are not de-duplicated here. Measured valid impressions of our tag or our script, less those whose browser could not measure ("nomeasure"); for our VAST, the impressions our Open Measurement script measured ("video" lines "om" or "view"). A pixel's impressions are never measured. Viewable valid "view" lines of our measurement (not a platform's viewable pixel, "m" Platform), and our VAST's "view". Viewability viewable / measured. Time in view the "ms" of valid "time" lines, added up, over the timed impressions: valid ones of our tag or script, less the unmeasurable. Shown in seconds per impression. Clicks, CTR valid "clk" lines; CTR = clicks / valid impressions. Interactions valid "int" lines, and a video that started ("video" "start"): in our VAST, or a tracked video counted by a pixel or our script; not outstream ("m" Served), which plays by itself. The interaction rate is of the valid impressions our tag or script ran (timed + unmeasurable), with the interactions counted by our tag or script ("m" Served or Script). IVT % invalid / impressions. Message seen "msgseen" over "msg" (Studio banners that could tell). What cannot be recounted from the lines, and why: Cost prices are not in the lines. Confirmed clicks and visits after a click or a view: the advertiser's site tag counts them on its own pages, and they are not journal lines. Reach and unique visitors: a line holds no visitor id, by design. Suspect share only a suspect's first sign counts, a rule the lines do not say. Ad serving alone campaigns: their impressions keep no lines (log-level data is Ad serving & tracking's), only their requests do. Lines the journal lost: a day it could not keep whole is not sealed, and a restart of up to 10 minutes can miss lines (see Help). Small differences are possible where the server caps a row (never more invalid than impressions on one row of the hour), and for days before 1.26.0. Python 3.6 or later, its standard library only (--tz: 3.9). Nothing is sent anywhere. """ import argparse import csv import datetime import gzip import json import sys from collections import defaultdict # The kinds of line (backend/Services/Journal/JournalLine.cs). REQ, IMP, VIEW, TIME, INT, DONE, CLK, IVT = "req", "imp", "view", "time", "int", "done", "clk", "ivt" MSG, MSGSEEN, NOMEASURE, VIDEO = "msg", "msgseen", "nomeasure", "video" SIGNALS = {VIEW, TIME, INT, DONE, CLK, MSG, MSGSEEN, NOMEASURE} OURS = {"Served", "Script"} # our tag and our measurement script: measured and timed RENDERED = {"Served", "Vast"} # what our tags serve: the render rate's FIELDS = ["requests", "served", "tracker_calls", "impressions", "rendered", "invalid", "valid", "measured", "unmeasurable", "viewable", "in_view_ms", "timed", "clicks", "invalid_clicks", "interactions", "interactions_ran", "ran", "completions", "message_measurable", "message_seen"] def read(paths): """Every line of the files, parsed, in order.""" for path in paths: opener = gzip.open if path.endswith(".gz") else open with opener(path, "rb") as f: for n, raw in enumerate(f, 1): raw = raw.strip() if not raw: continue try: yield json.loads(raw.decode("utf-8")) except ValueError: sys.stderr.write("{}:{}: not a line of the journal, skipped\n".format(path, n)) def hour_of(line): """The hour a figure counts in: the impression's served hour when the line has one, else the line's own.""" sh = line.get("sh") if sh: return datetime.datetime.strptime(sh, "%Y-%m-%dT%H:00Z").replace(tzinfo=datetime.timezone.utc) return own_hour(line) def own_hour(line): t = datetime.datetime.fromtimestamp(line["t"] / 1000.0, tz=datetime.timezone.utc) return t.replace(minute=0, second=0, microsecond=0) def recount(lines, zone=None): """The figures by (day, campaign, placement, creative), and the UTC days the lines were written on.""" lines = list(lines) days_read = {own_hour(l).date() for l in lines} def day(hour): return (hour.astimezone(zone) if zone else hour).date() rows = defaultdict(lambda: dict.fromkeys(FIELDS, 0)) om = set() # VAST impressions measured, by nonce: an "om" and then a "view" are one for l in lines: e = l.get("e") m = l.get("m", "") key = lambda h: (day(h), l.get("c"), l.get("pl"), l.get("cr")) if e == REQ: r = rows[key(own_hour(l))] r["requests"] += 1 if l.get("o") == "Served": r["served"] += 1 continue # a platform's preview and a test host are no one's traffic: in none of the figures since 4.6.0 (021-tests-apart.sql) if (l.get("ivt") or "").lower() in ("adreview", "unverifiedhost"): continue if e == IMP: if not l.get("sh"): # a tracker's call: its request is counted when it is, in that hour r = rows[key(own_hour(l))] r["requests"] += 1 r["tracker_calls"] += 1 r = rows[key(hour_of(l))] r["impressions"] += 1 if m in RENDERED: r["rendered"] += 1 if l.get("ivt"): r["invalid"] += 1 elif m in OURS: r["timed"] += 1 continue r = rows[key(hour_of(l))] if e == IVT: r["invalid"] += 1 if m in OURS: r["timed"] -= 1 continue if e == VIDEO: sign, k = l.get("sign"), l.get("k", "") if sign in ("om", "view") and (k, hour_of(l)) not in om: om.add((k, hour_of(l))) r["measured"] += 1 if sign == "view": r["viewable"] += 1 elif sign == "start" and m != "Served": # a video that played: our VAST's or a tracked one's; outstream plays by itself, its start is no interaction r["interactions"] += 1 if m in OURS: r["interactions_ran"] += 1 elif sign == "complete": r["completions"] += 1 continue if e not in SIGNALS: continue if l.get("ivt"): if e == CLK: r["invalid_clicks"] += 1 continue if e == VIEW and m != "Platform": r["viewable"] += 1 elif e == TIME: r["in_view_ms"] += int(l.get("ms", 0)) elif e == CLK: r["clicks"] += 1 elif e == INT: r["interactions"] += 1 if m in OURS: r["interactions_ran"] += 1 elif e == DONE: r["completions"] += 1 elif e == MSG: r["message_measurable"] += 1 elif e == MSGSEEN: r["message_seen"] += 1 elif e == NOMEASURE and m in OURS: r["unmeasurable"] += 1 for r in rows.values(): r["valid"] = max(0, r["impressions"] - r["invalid"]) # our tag's and script's valid impressions ran our code: the interaction rate's base, measured and timed but the unmeasurable r["ran"] = max(0, r["timed"]) r["timed"] = max(0, r["timed"] - r["unmeasurable"]) r["measured"] += r["timed"] return rows, days_read def rates(r): """The rates the report shows, from the counts: None where there is no base.""" def pct(a, b, digits=2): return round(100.0 * a / b, digits) if b > 0 else None return { "render_rate": pct(r["rendered"], r["served"], 1) if r["rendered"] <= r["served"] else None, "viewability": pct(min(r["viewable"], r["measured"]), r["measured"], 1), "time_in_view_s": round(r["in_view_ms"] / 1000.0 / r["timed"], 1) if r["timed"] > 0 and r["in_view_ms"] > 0 else None, "ctr": pct(r["clicks"], r["valid"], 2), "interaction_rate": pct(min(r["interactions_ran"], r["ran"]), r["ran"], 2), "ivt": pct(r["invalid"], r["impressions"], 2), "message_seen_rate": pct(r["message_seen"], r["message_measurable"], 1), } COLUMNS = [("Requests", "requests"), ("Served", "served"), ("Impressions", "impressions"), ("Rendered", "rendered"), ("Render rate %", "render_rate"), ("Invalid", "invalid"), ("Valid", "valid"), ("Measured", "measured"), ("Unmeasurable", "unmeasurable"), ("Viewable", "viewable"), ("Viewability %", "viewability"), ("Time in view (s)", "time_in_view_s"), ("Clicks", "clicks"), ("CTR %", "ctr"), ("Interactions", "interactions"), ("Interaction rate %", "interaction_rate"), ("IVT %", "ivt"), ("Completions", "completions"), ("Message measurable", "message_measurable"), ("Message seen", "message_seen"), ("Message seen %", "message_seen_rate")] CSV_EXTRA = [("Tracker calls", "tracker_calls"), ("Time in view (ms)", "in_view_ms"), ("Timed", "timed"), ("Ran our code", "ran"), ("Interactions of those", "interactions_ran"), ("Invalid clicks", "invalid_clicks")] def total(rows): t = dict.fromkeys(FIELDS, 0) for r in rows: for f in FIELDS: t[f] += r[f] return t def cell(v): if v is None: return "-" return "{:,}".format(v) if isinstance(v, int) else str(v) def main(argv): ap = argparse.ArgumentParser(description="Recount a CreativeRoll report from downloaded ledger days.", add_help=True) ap.add_argument("files", nargs="*") ap.add_argument("--day", action="append", default=[], help="YYYY-MM-DD: only this day (UTC, or of --tz)") ap.add_argument("--tz", help="IANA time zone of the agency, to group by its own day") ap.add_argument("--campaign", type=int, help="only this campaign") ap.add_argument("--csv", action="store_true", help="CSV instead of a table") args = ap.parse_args(argv[1:]) if not args.files: sys.stderr.write(__doc__) return 2 zone = None if args.tz: try: from zoneinfo import ZoneInfo zone = ZoneInfo(args.tz) except ImportError: sys.stderr.write("--tz needs Python 3.9 or later (zoneinfo).\n") return 2 except Exception: sys.stderr.write("Unknown time zone: {}\n".format(args.tz)) return 2 try: wanted = {datetime.date.fromisoformat(d) if hasattr(datetime.date, "fromisoformat") else datetime.datetime.strptime(d, "%Y-%m-%d").date() for d in args.day} except ValueError: sys.stderr.write("--day takes YYYY-MM-DD.\n") return 2 rows, days_read = recount(read(args.files), zone) keys = sorted((k for k in rows if (not wanted or k[0] in wanted) and (args.campaign is None or k[1] == args.campaign)), key=lambda k: (k[0], k[1] or 0, k[2] or 0, k[3] or 0)) chosen = [rows[k] for k in keys] t = total(chosen) if args.csv: w = csv.writer(sys.stdout, lineterminator="\n") w.writerow(["Day", "Campaign", "Placement", "Creative"] + [h for h, _ in COLUMNS + CSV_EXTRA]) for k, r in list(zip(keys, chosen)) + [(("Total", "", "", ""), t)]: shown = dict(r, **rates(r)) w.writerow([str(k[0]), "" if k[1] is None else k[1], "" if k[2] is None else k[2], "" if k[3] is None else k[3]] + ["" if shown[f] is None else shown[f] for _, f in COLUMNS + CSV_EXTRA]) return 0 zone_name = args.tz or "UTC" print("Days read (UTC): {}".format(", ".join(str(d) for d in sorted(days_read)) or "none")) print("Grouped by the day in: {}".format(zone_name)) head = ["Day", "Campaign", "Placement", "Creative"] + [h for h, _ in COLUMNS] table = [head] for k, r in zip(keys, chosen): shown = dict(r, **rates(r)) table.append([str(k[0]), cell(k[1]), cell(k[2]), cell(k[3])] + [cell(shown[f]) for _, f in COLUMNS]) shown = dict(t, **rates(t)) table.append(["Total", "", "", ""] + [cell(shown[f]) for _, f in COLUMNS]) widths = [max(len(row[i]) for row in table) for i in range(len(head))] for n, row in enumerate(table): print(" ".join(c.ljust(widths[i]) if i < 4 else c.rjust(widths[i]) for i, c in enumerate(row))) if n == 0 or n == len(table) - 2: print(" ".join("-" * w for w in widths)) # A day whose own file, or the next one with its late events, was not read is partial. utc_days = {k[0] for k in keys} if zone is None else set() partial = sorted(d for d in utc_days if d not in days_read or d + datetime.timedelta(days=1) not in days_read) if partial: print("\nPartial: {} (its file, or the next day's with its late events, was not read).".format(", ".join(str(d) for d in partial))) if zone is not None: print("\nA local day spans two UTC days: read every UTC day it touches, and the day after.") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))