diff --git a/backfill.py b/backfill.py index 17bf4af..9fd890f 100644 --- a/backfill.py +++ b/backfill.py @@ -189,6 +189,21 @@ def targets(margin_deg=0.15, fuel=None): return bbox, ids +def year_is_complete(year, state): + """Une année marquée réussie reste « complète » seulement si ses lignes sont présentes. + + ``stored`` (lignes réellement écrites lors de l'import) sert de référence. Sans référence + exploitable, l'année est considérée incomplète : la restauration est idempotente, l'import + utilise ``INSERT OR IGNORE`` et ne crée aucun doublon. + """ + if not state or state.get("status") != "ok": + return False + expected = int(state.get("stored") or 0) + if expected <= 0: + return False + return storage.archive_rows_present(year) >= expected + + def backfill(years=None, fuels=DEFAULT_FUELS, progress=None, refresh_current=True, force=False): """Importe les archives annuelles. Idempotent et reprenable année par année.""" progress = progress or (lambda message: None) @@ -199,9 +214,12 @@ def backfill(years=None, fuels=DEFAULT_FUELS, progress=None, refresh_current=Tru summary = dict(years=[], stations=0, imported=0, skipped=0, failures=[]) for year in years: state = done.get(year) - if state and state["status"] == "ok" and year < current_year and not force: + if year < current_year and not force and year_is_complete(year, state): summary["skipped"] += 1 continue + if state and state["status"] == "ok": + # Une réussite enregistrée ne prouve pas que les lignes sont encore là. + summary.setdefault("restored", []).append(year) if year == current_year and not refresh_current and state: summary["skipped"] += 1 continue @@ -220,7 +238,7 @@ def backfill(years=None, fuels=DEFAULT_FUELS, progress=None, refresh_current=Tru f"{len(stations)} station(s) ciblée(s), {len(rows)} prix jour retenus, " f"{imported} nouvelles lignes, {len(absent)} station(s) sans prix dans l'année" ) - storage.save_backfill_run(year, "ok", len(stations), len(rows), detail) + storage.save_backfill_run(year, "ok", len(stations), len(rows), detail, stored=imported) summary["years"].append(dict(year=year, stations=len(stations), rows=len(rows), imported=imported)) summary["stations"] = max(summary["stations"], len(stations)) summary["imported"] += imported diff --git a/collector.py b/collector.py index e4ceb6f..cc1d097 100644 --- a/collector.py +++ b/collector.py @@ -23,6 +23,30 @@ EU_SOURCE = "Commission européenne – Weekly Oil Bulletin (hebdomadaire)" PORTWATCH_SOURCE = "IMF PortWatch (quotidien, publication différée)" MARKET_SOURCE = "Cotation de marché (quotidienne, voir marché amont)" +# Rétention courte : **liste blanche** des origines purgables, jamais un motif d'exclusion. +# Les archives officielles importées (`archive:`) et toute future origine historique +# doivent être ajoutées explicitement ici avant de pouvoir être purgées. +PURGEABLE_ORIGINS = ("live",) +_PURGE_OBSERVATIONS = ( + "DELETE FROM observations WHERE day 'real'" + " OR price IS NULL OR price <= 0 OR day NOT LIKE '____-__-__'" + ).fetchone()[0] + return dict( + published_at_renseignes=numeric, + published_at_non_dates=bad_published, + fetched_at_permute=swapped_fetch, + fetched_at_absent=missing_fetch, + lignes_incoherentes=other, + ) + + +def repair(apply=False, now=None): + before = survey(now) + if not apply: + return dict(applied=False, avant=before) + with storage.connect() as db: + cleared = db.execute( + "UPDATE observations SET published_at=NULL WHERE published_at IS NOT NULL AND (" + "length(published_at) < 10 OR published_at NOT LIKE '____-__-__%')" + ).rowcount + fixed = db.execute( + "UPDATE observations SET fetched_at=collected_at WHERE fetched_at IS NOT NULL" + " AND fetched_at = source_updated AND collected_at IS NOT NULL" + ).rowcount + storage.record_maintenance( + "repair_observation_columns", + int(cleared) + int(fixed), + f"published_at remis a NULL: {cleared} ; fetched_at restaure depuis collected_at: {fixed}", + now=now, + ) + after = survey(now) + return dict(applied=True, cleared_published_at=cleared, restored_fetched_at=fixed, + avant=before, apres=after) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--apply", action="store_true", help="écrire les corrections") + args = parser.parse_args() + print(json.dumps(repair(apply=args.apply), ensure_ascii=False, indent=2)) diff --git a/storage.py b/storage.py index 2b2bafe..8d51f63 100644 --- a/storage.py +++ b/storage.py @@ -5,6 +5,7 @@ from __future__ import annotations import json import math import os +import re import sqlite3 import statistics from contextlib import contextmanager @@ -16,6 +17,32 @@ PARIS = ZoneInfo("Europe/Paris") MAX_PRICE_AGE_DAYS = 7 +_NUMERIC = re.compile(r"[-+]?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") + + +def valid_published_at(value): + """Date/heure de publication, ou None. **Un prix n'est jamais une date.** + + L'ancien bug positionnel de ``record_observations`` écrivait le prix dans cette colonne : + la validation refuse explicitement une valeur numérique, plutôt que de la laisser passer. + """ + if value is None: + return None + text = str(value).strip() + if not text: + return None + if _NUMERIC.fullmatch(text): + raise ValueError(f"published_at ressemble à un prix, pas à une date : {text[:32]!r}") + try: + if len(text) == 10: + date.fromisoformat(text) + else: + datetime.fromisoformat(text.replace(" ", "T")) + except ValueError: + raise ValueError(f"published_at n'est pas une date valide : {text[:32]!r}") from None + return text + + def observation_not_future(value, now=None): """Refuse une observation future (tolérance explicite 5 min pour collecte/horloges). @@ -67,7 +94,10 @@ def record_observations(rows, now=None): key = (row["id"], fuel, day) values[key] = (*key, price, row["updates"].get(fuel, ""), now.isoformat(), row["lat"], row["lon"]) with connect() as db: - rows_with_meta = [(*value, value[3], value[4]) for value in values.values()] + # published_at reste vide : le flux instantané ne publie pas de date de publication, + # seulement l'horodatage déclaré par la station (``source_updated``). ``fetched_at`` porte + # notre propre téléchargement. L'ancien code y écrivait le prix et la date déclarée. + rows_with_meta = [(*value, valid_published_at(None), value[5]) for value in values.values()] db.executemany( """INSERT INTO observations(station_id,fuel,day,price,source_updated,collected_at,lat,lon, published_at,fetched_at) VALUES(?,?,?,?,?,?,?,?,?,?) @@ -154,7 +184,7 @@ def save_upstream(series, rows, unit, source, now=None): str(source), now.isoformat(), str(row.get("observed_at") or row["day"]), - row.get("published_at"), + valid_published_at(row.get("published_at")), ) for row in rows if row.get("day") @@ -632,15 +662,51 @@ def save_archive_observations(rows, origin, now=None): return after - before -def save_backfill_run(year, status, stations, prices, detail="", now=None): +def save_backfill_run(year, status, stations, prices, detail="", now=None, stored=0): + """``prices`` = lignes lues dans l'archive, ``stored`` = lignes réellement écrites. + + ``stored`` est la référence de complétude : une année marquée réussie dont il ne reste + plus ``stored`` lignes doit être restaurée. + """ stamp = (now or datetime.now(timezone.utc)).isoformat() with connect() as db: db.execute( - "REPLACE INTO backfill_runs(year,status,stations,prices,finished_at,detail) VALUES(?,?,?,?,?,?)", - (year, status, stations, prices, stamp, detail), + "REPLACE INTO backfill_runs(year,status,stations,prices,stored,finished_at,detail)" + " VALUES(?,?,?,?,?,?,?)", + (year, status, stations, prices, int(stored or 0), stamp, detail), ) +def archive_rows_present(year): + """Lignes d'archive encore présentes pour une année (contrôle de complétude).""" + with connect() as db: + row = db.execute( + "SELECT count(*) FROM observations WHERE origin=?", (f"archive:{int(year)}",) + ).fetchone() + return int(row[0]) if row else 0 + + +def record_maintenance(operation, affected, detail="", now=None): + """Trace d'une opération de maintenance (nombre de lignes touchées, jamais de secret).""" + stamp = (now or datetime.now(timezone.utc)).isoformat() + with connect() as db: + db.execute( + "INSERT INTO db_maintenance(operation,affected,detail,done_at) VALUES(?,?,?,?)", + (str(operation)[:80], int(affected), str(detail)[:300], stamp), + ) + return True + + +def maintenance_log(limit=20): + with connect() as db: + return [ + dict(row) + for row in db.execute( + "SELECT * FROM db_maintenance ORDER BY done_at DESC LIMIT ?", (int(limit),) + ) + ] + + def backfill_runs(): with connect() as db: return {row["year"]: dict(row) for row in db.execute("SELECT * FROM backfill_runs ORDER BY year")} @@ -1274,7 +1340,11 @@ def connect(): duration_s REAL, provider TEXT NOT NULL, computed_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS backfill_runs ( year INTEGER PRIMARY KEY, status TEXT NOT NULL, stations INTEGER DEFAULT 0, - prices INTEGER DEFAULT 0, finished_at TEXT NOT NULL, detail TEXT DEFAULT ''); + prices INTEGER DEFAULT 0, finished_at TEXT NOT NULL, detail TEXT DEFAULT '', + stored INTEGER DEFAULT 0); + CREATE TABLE IF NOT EXISTS db_maintenance ( + operation TEXT NOT NULL, affected INTEGER NOT NULL, detail TEXT DEFAULT '', + done_at TEXT NOT NULL); CREATE TABLE IF NOT EXISTS forecasts ( id INTEGER PRIMARY KEY AUTOINCREMENT, fuel TEXT NOT NULL, direction TEXT NOT NULL, change_low REAL, change_high REAL, days_min INTEGER, days_max INTEGER, @@ -1314,6 +1384,11 @@ def connect(): }, ) _ensure_columns(db, "news_articles", {"skip_reason": "TEXT"}) + _ensure_columns(db, "backfill_runs", {"stored": "INTEGER DEFAULT 0"}) + db.execute( + "CREATE TABLE IF NOT EXISTS db_maintenance (operation TEXT NOT NULL," + " affected INTEGER NOT NULL, detail TEXT DEFAULT '', done_at TEXT NOT NULL)" + ) yield db finally: db.close() diff --git a/tests/test_backfill_restore.py b/tests/test_backfill_restore.py new file mode 100644 index 0000000..fdd6cf1 --- /dev/null +++ b/tests/test_backfill_restore.py @@ -0,0 +1,49 @@ +"""Une année marquée réussie ne prouve rien : le backfill doit pouvoir la restaurer.""" + +from test_backfill import archive_bytes + +import backfill +import storage + + +def prepare(monkeypatch): + monkeypatch.setattr(backfill, "download_year", lambda year, timeout=None: archive_bytes()) + monkeypatch.setattr(backfill, "targets", lambda margin_deg=0.15, fuel=None: (None, set())) + + +def test_incomplete_year_is_not_considered_done(store): + """Le bug : statut ok + lignes disparues => l'année doit repartir en import.""" + assert backfill.year_is_complete(2007, None) is False + assert backfill.year_is_complete(2007, {"status": "ok", "stored": 0}) is False + assert backfill.year_is_complete(2007, {"status": "ok", "stored": 5}) is False + with store.connect() as db: + db.execute( + "INSERT INTO observations VALUES('1','Gazole','2007-01-04',1.0,'2007-01-04T10:00:00'," + "'2026-09-15T09:00:00',44.0,-0.5,NULL,NULL,'archive:2007')" + ) + assert backfill.year_is_complete(2007, {"status": "ok", "stored": 1}) is True + + +def test_disappeared_year_is_restored_without_duplicates(store, monkeypatch): + prepare(monkeypatch) + first = backfill.backfill(years=[2007]) + imported = first["years"][0]["imported"] + assert imported > 0 + assert store.archive_rows_present(2007) == imported + + # Incident de purge : l'année disparaît alors que backfill_runs reste « ok ». + with store.connect() as db: + db.execute("DELETE FROM observations WHERE origin='archive:2007'") + assert store.archive_rows_present(2007) == 0 + assert storage.backfill_runs()[2007]["status"] == "ok" + assert storage.backfill_runs()[2007]["stored"] == imported + + restored = backfill.backfill(years=[2007]) + assert restored["restored"] == [2007] + assert store.archive_rows_present(2007) == imported + + # Idempotent : une seconde passe ne recrée aucun doublon. + again = backfill.backfill(years=[2007]) + assert again["years"] == [] + assert again["skipped"] == 1 + assert store.archive_rows_present(2007) == imported diff --git a/tests/test_published_at.py b/tests/test_published_at.py new file mode 100644 index 0000000..dc2df31 --- /dev/null +++ b/tests/test_published_at.py @@ -0,0 +1,77 @@ +"""published_at ne doit jamais contenir un prix : validation, ingestion, réparation.""" + +from datetime import datetime, timezone + +import pytest + +import repair_columns +import storage + +COLUMNS = "station_id,fuel,day,price,source_updated,collected_at,lat,lon,published_at,fetched_at,origin" + + +def test_price_is_refused_as_publication_date(store): + with pytest.raises(ValueError, match="prix"): + store.valid_published_at("0.817") + with pytest.raises(ValueError, match="prix"): + store.valid_published_at("2.829") + with pytest.raises(ValueError, match="date valide"): + store.valid_published_at("pas une date") + assert store.valid_published_at(None) is None + assert store.valid_published_at("") is None + assert store.valid_published_at("2026-09-04") == "2026-09-04" + assert store.valid_published_at("2026-09-04T13:00:00+00:00").startswith("2026-09-04T13") + + +def test_record_observations_writes_dates_not_prices(store): + rows = [ + dict(id="1", lat=44.0, lon=-0.5, prices={"Gazole": 1.719}, updates={"Gazole": "2026-09-01T08:00:00"}) + ] + assert store.record_observations(rows) == 1 + with store.connect() as db: + row = db.execute("SELECT * FROM observations").fetchone() + assert row["published_at"] is None + assert row["fetched_at"] == row["collected_at"] + assert row["fetched_at"] != row["source_updated"] + assert row["source_updated"] == "2026-09-01T08:00:00" + assert row["price"] == pytest.approx(1.719) + + +def test_repair_clears_legacy_corruption(store): + """Reproduit l'ancien bug positionnel, puis vérifie la réparation et sa trace.""" + with store.connect() as db: + db.execute( + f"INSERT INTO observations({COLUMNS}) VALUES(?,?,?,?,?,?,?,?,?,?,?)", + ( + "1", + "Gazole", + "2026-09-14", + 1.719, + "2026-09-14T08:00:00", + "2026-09-14T09:00:00", + 44.0, + -0.5, + "1.719", + "2026-09-14T08:00:00", + "live", + ), + ) + survey = repair_columns.survey() + assert survey["published_at_non_dates"] == 1 + assert survey["fetched_at_permute"] == 1 + + assert repair_columns.repair(apply=False)["applied"] is False + + result = repair_columns.repair(apply=True, now=datetime(2026, 9, 15, tzinfo=timezone.utc)) + assert result["cleared_published_at"] == 1 + assert result["restored_fetched_at"] == 1 + assert result["apres"]["published_at_non_dates"] == 0 + assert result["apres"]["fetched_at_permute"] == 0 + with store.connect() as db: + row = db.execute("SELECT * FROM observations").fetchone() + assert row["published_at"] is None + assert row["fetched_at"] == "2026-09-14T09:00:00" + assert row["price"] == pytest.approx(1.719) + trace = storage.maintenance_log() + assert trace and trace[0]["operation"] == "repair_observation_columns" + assert trace[0]["affected"] == 2 diff --git a/tests/test_retention.py b/tests/test_retention.py new file mode 100644 index 0000000..4b05685 --- /dev/null +++ b/tests/test_retention.py @@ -0,0 +1,57 @@ +"""Rétention : seules les collectes courantes sont purgées, jamais les archives.""" + +from datetime import datetime, timezone + +import collector + +COLUMNS = "station_id,fuel,day,price,source_updated,collected_at,lat,lon,published_at,fetched_at,origin" + + +def insert(store, station, day, origin, declared="2026-09-15T08:00:00", price=1.7): + with store.connect() as db: + db.execute( + f"INSERT INTO observations({COLUMNS}) VALUES(?,?,?,?,?,?,?,?,?,?,?)", + ( + station, + "Gazole", + day, + price, + declared, + "2026-09-15T09:00:00", + 44.0, + -0.5, + None, + "2026-09-15T09:00:00", + origin, + ), + ) + + +def test_old_archive_row_survives_purge(store): + """Une archive de 2008 doit survivre même vieille de plus de 730 jours.""" + insert(store, "1", "2008-05-05", "archive:2008") + insert(store, "2", "2026-09-10", "live") + purged = collector.purge_old_observations(now=datetime(2026, 9, 15, tzinfo=timezone.utc)) + assert purged == 0 + assert store.archive_rows_present(2008) == 1 + with store.connect() as db: + assert db.execute("SELECT count(*) FROM observations").fetchone()[0] == 2 + + +def test_old_live_row_is_purged(store): + """La collecte courante, elle, reste soumise à la rétention.""" + insert(store, "1", "2024-01-01", "live") + insert(store, "2", "2024-01-01", "archive:2024") + purged = collector.purge_old_observations(now=datetime(2026, 9, 15, tzinfo=timezone.utc)) + assert purged == 1 + with store.connect() as db: + remaining = [row[0] for row in db.execute("SELECT origin FROM observations")] + assert remaining == ["archive:2024"] + + +def test_unknown_origin_is_never_purged(store): + """Seule la liste blanche est purgée : une origine non déclarée est conservée.""" + insert(store, "9", "2015-01-01", "future:origine") + assert collector.purge_old_observations(now=datetime(2026, 9, 15, tzinfo=timezone.utc)) == 0 + with store.connect() as db: + assert db.execute("SELECT count(*) FROM observations").fetchone()[0] == 1