mirror of
https://github.com/elder-plinius/OBLITERATUS.git
synced 2026-12-05 02:24:12 +01:00
On Python 3.13+, an sqlite3 connection that is garbage-collected without being closed raises ResourceWarning, which the project's filterwarnings=error turns into test failures. pyproject declares requires-python >=3.11 with no upper bound, so these versions must work. - The durable study's RDBStorage is now owned by an ExitStack in both public entry points and closed (remove_session, then engine.dispose) on success, failure and cancellation. - _atomic_sqlite_backup closes both handles with contextlib.closing; sqlite3's own context manager only ends the transaction. - Two tests that reopened or connected to study databases now close their handles. - New regression test tracks every sqlite3 handle opened during a real durable study (success, failure, KeyboardInterrupt) and the backup, asserting all are closed independent of the 3.13+ warning. Storage URLs, file names, snapshots and resume behaviour are unchanged; as with any edit to this module, the study identity (which hashes the module source) changes, so pre-existing durable studies start fresh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
89 lines
3.6 KiB
Python
89 lines
3.6 KiB
Python
"""Failed evidence publication preserves the previous durable checkpoint."""
|
|
|
|
from contextlib import closing
|
|
import json
|
|
from pathlib import Path
|
|
import sqlite3
|
|
from types import SimpleNamespace
|
|
from unittest.mock import Mock
|
|
|
|
import optuna
|
|
import pytest
|
|
|
|
from obliteratus import bayesian_optimizer as bo
|
|
|
|
pytestmark = pytest.mark.cpu
|
|
|
|
|
|
@pytest.mark.parametrize("kind", ["json", "sqlite"])
|
|
@pytest.mark.parametrize("temporary_disappears", [False, True])
|
|
def test_failed_atomic_publish_preserves_checkpoint_and_removes_temporary(
|
|
monkeypatch, tmp_path, kind, temporary_disappears,
|
|
):
|
|
destination = tmp_path / "retained-checkpoint"
|
|
previous = b"previous retained bytes"
|
|
destination.write_bytes(previous)
|
|
source = tmp_path / "live.sqlite3"
|
|
with closing(sqlite3.connect(source)) as connection, connection:
|
|
connection.execute("CREATE TABLE evidence (value TEXT)")
|
|
connection.execute("INSERT INTO evidence VALUES ('completed')")
|
|
error = OSError("publication unavailable")
|
|
|
|
def fail_publish(temporary, final):
|
|
assert Path(final) == destination
|
|
assert Path(temporary).stat().st_size > 0
|
|
if temporary_disappears:
|
|
Path(temporary).unlink()
|
|
raise error
|
|
|
|
monkeypatch.setattr(bo.os, "replace", fail_publish)
|
|
with pytest.raises(OSError) as caught:
|
|
if kind == "json":
|
|
bo._atomic_json(destination, {"state": "COMPLETE"})
|
|
else:
|
|
bo._atomic_sqlite_backup(source, destination)
|
|
assert caught.value is error
|
|
assert destination.read_bytes() == previous
|
|
assert not list(tmp_path.glob(f".{destination.name}.*"))
|
|
with closing(sqlite3.connect(source)) as connection, connection:
|
|
assert connection.execute("SELECT value FROM evidence").fetchall() == [("completed",)]
|
|
|
|
|
|
@pytest.mark.parametrize("attrs,values", [({}, [.2, .1]), ({"plan_sha256": "plan"}, None)])
|
|
def test_unscored_trial_cannot_publish_a_completed_receipt(tmp_path, attrs, values):
|
|
publish = Mock()
|
|
checkpoint = Mock()
|
|
pipeline = SimpleNamespace(_on_bayesian_trial=publish, _bayesian_trial_checkpoint=checkpoint)
|
|
trial = SimpleNamespace(state=SimpleNamespace(name="COMPLETE"), values=values, user_attrs=attrs)
|
|
bo._persist_completed_trial(pipeline, trial, study_identity="study", evidence_path=tmp_path / "study.json")
|
|
assert list(tmp_path.iterdir()) == []
|
|
publish.assert_not_called()
|
|
checkpoint.assert_not_called()
|
|
|
|
|
|
def test_publication_requires_durable_local_receipt():
|
|
publish = Mock()
|
|
trial = SimpleNamespace(
|
|
state=SimpleNamespace(name="COMPLETE"), number=0, values=[.2, .1],
|
|
params={}, distributions={}, user_attrs={"plan_sha256": "plan"},
|
|
)
|
|
with pytest.raises(RuntimeError, match="requires durable local evidence"):
|
|
bo._persist_completed_trial(
|
|
SimpleNamespace(_on_bayesian_trial=publish), trial,
|
|
study_identity="study", evidence_path=None,
|
|
)
|
|
publish.assert_not_called()
|
|
|
|
|
|
@pytest.mark.parametrize("suffix,number", [("not-a-number", 0), ("-1", -1), ("0", True), ("1", 0)])
|
|
def test_malformed_receipt_identity_cannot_add_trials(tmp_path, suffix, number):
|
|
(tmp_path / f"study.trial-{suffix}.json").write_text(json.dumps({
|
|
"schema": bo._STUDY_SCHEMA, "study_identity": "study", "state": "COMPLETE",
|
|
"trial_number": number, "values": [.2, .1], "parameters": {},
|
|
"distributions": {}, "user_attrs": {"plan_sha256": "plan"},
|
|
}))
|
|
study = optuna.create_study(directions=["minimize", "minimize"])
|
|
with pytest.raises(RuntimeError, match="invalid Bayesian recovery receipt"):
|
|
bo._restore_completed_trials(optuna, study, tmp_path / "study.json", "study")
|
|
assert study.trials == []
|