|
| 1 | +""" |
| 2 | +Cleanup in ``Job.refresh()`` (#1577). |
| 3 | +
|
| 4 | +``refresh(*restrictions)`` narrows the keys it adds, but the cleanup must judge |
| 5 | +which keys have vanished against the full ``key_source``: jobs outside the |
| 6 | +restriction -- reserved by other workers, or recording errors -- are not stale. |
| 7 | +``success`` and ``error`` records whose key has left both ``key_source`` and the |
| 8 | +target are removed on refresh, in one statement rather than one per key. |
| 9 | +""" |
| 10 | + |
| 11 | +import time |
| 12 | +from datetime import datetime |
| 13 | + |
| 14 | +import pytest |
| 15 | + |
| 16 | +import datajoint as dj |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture(scope="function") |
| 20 | +def schema_by_backend(connection_by_backend, db_creds_by_backend): |
| 21 | + """Create a fresh schema per test, parameterized across backends.""" |
| 22 | + backend = db_creds_by_backend["backend"] |
| 23 | + test_id = str(int(time.time() * 1000))[-8:] |
| 24 | + schema_name = f"djtest_jobsrefresh_{backend}_{test_id}"[:64] |
| 25 | + |
| 26 | + if connection_by_backend.is_connected: |
| 27 | + try: |
| 28 | + connection_by_backend.query( |
| 29 | + f"DROP DATABASE IF EXISTS {connection_by_backend.adapter.quote_identifier(schema_name)}" |
| 30 | + ) |
| 31 | + except Exception: |
| 32 | + pass |
| 33 | + |
| 34 | + schema = dj.Schema(schema_name, connection=connection_by_backend) |
| 35 | + yield schema |
| 36 | + |
| 37 | + if connection_by_backend.is_connected: |
| 38 | + try: |
| 39 | + connection_by_backend.query( |
| 40 | + f"DROP DATABASE IF EXISTS {connection_by_backend.adapter.quote_identifier(schema_name)}" |
| 41 | + ) |
| 42 | + except Exception: |
| 43 | + pass |
| 44 | + |
| 45 | + |
| 46 | +@pytest.fixture |
| 47 | +def pipeline(schema_by_backend): |
| 48 | + @schema_by_backend |
| 49 | + class Raw(dj.Manual): |
| 50 | + definition = """ |
| 51 | + raw_id : int32 |
| 52 | + --- |
| 53 | + v : float32 |
| 54 | + """ |
| 55 | + |
| 56 | + @schema_by_backend |
| 57 | + class Proc(dj.Computed): |
| 58 | + definition = """ |
| 59 | + -> Raw |
| 60 | + --- |
| 61 | + w : float32 |
| 62 | + """ |
| 63 | + |
| 64 | + def make(self, key): |
| 65 | + self.insert1(dict(key, w=2 * (Raw & key).fetch1("v"))) |
| 66 | + |
| 67 | + return Raw, Proc |
| 68 | + |
| 69 | + |
| 70 | +def _statuses(jobs): |
| 71 | + """Map raw_id to job status.""" |
| 72 | + return {row["raw_id"]: row["status"] for row in jobs.proj("status").to_dicts()} |
| 73 | + |
| 74 | + |
| 75 | +def _backdate(jobs): |
| 76 | + """Make every job older than the default stale_timeout.""" |
| 77 | + for key in jobs.keys(): |
| 78 | + jobs.update1({**key, "created_time": datetime(2000, 1, 1)}) |
| 79 | + |
| 80 | + |
| 81 | +def test_restricted_refresh_keeps_jobs_outside_restriction(pipeline): |
| 82 | + """A restricted refresh leaves other workers' reservations and errors alone.""" |
| 83 | + Raw, Proc = pipeline |
| 84 | + Raw.insert([dict(raw_id=i, v=float(i)) for i in range(4)]) |
| 85 | + Proc.jobs.refresh() |
| 86 | + assert Proc.jobs.reserve({"raw_id": 1}) # held by another worker |
| 87 | + assert Proc.jobs.reserve({"raw_id": 2}) |
| 88 | + Proc.jobs.error({"raw_id": 2}, "failed") |
| 89 | + (Raw & {"raw_id": 3}).delete(prompt=False) # pending job for a vanished key |
| 90 | + _backdate(Proc.jobs) |
| 91 | + |
| 92 | + result = Proc.jobs.refresh({"raw_id": 0}) |
| 93 | + |
| 94 | + assert _statuses(Proc.jobs) == {0: "pending", 1: "reserved", 2: "error"} |
| 95 | + assert result["removed"] == 1 |
| 96 | + |
| 97 | + |
| 98 | +def test_restricted_populate_keeps_jobs_outside_restriction(pipeline): |
| 99 | + """``populate(restriction, reserve_jobs=True)`` refreshes with the restriction.""" |
| 100 | + Raw, Proc = pipeline |
| 101 | + Raw.insert([dict(raw_id=i, v=float(i)) for i in range(3)]) |
| 102 | + Proc.jobs.refresh() |
| 103 | + assert Proc.jobs.reserve({"raw_id": 1}) |
| 104 | + assert Proc.jobs.reserve({"raw_id": 2}) |
| 105 | + Proc.jobs.error({"raw_id": 2}, "failed") |
| 106 | + _backdate(Proc.jobs) |
| 107 | + |
| 108 | + Proc.populate({"raw_id": 0}, reserve_jobs=True) |
| 109 | + |
| 110 | + assert len(Proc()) == 1 |
| 111 | + assert _statuses(Proc.jobs) == {1: "reserved", 2: "error"} |
| 112 | + |
| 113 | + |
| 114 | +def test_refresh_removes_records_of_vanished_keys(pipeline): |
| 115 | + """Success and error records whose upstream row was deleted go on the next refresh.""" |
| 116 | + Raw, Proc = pipeline |
| 117 | + with dj.config.override(jobs={"keep_completed": True}): |
| 118 | + Raw.insert([dict(raw_id=i, v=float(i)) for i in range(3)]) |
| 119 | + Proc.populate(reserve_jobs=True) |
| 120 | + Raw.insert1(dict(raw_id=3, v=3.0)) |
| 121 | + Proc.jobs.refresh() |
| 122 | + assert Proc.jobs.reserve({"raw_id": 3}) |
| 123 | + Proc.jobs.error({"raw_id": 3}, "failed") |
| 124 | + assert _statuses(Proc.jobs) == {0: "success", 1: "success", 2: "success", 3: "error"} |
| 125 | + |
| 126 | + (Raw & "raw_id in (0, 3)").delete(prompt=False) |
| 127 | + result = Proc.jobs.refresh() # records are fresh: no stale_timeout involved |
| 128 | + |
| 129 | + assert _statuses(Proc.jobs) == {1: "success", 2: "success"} |
| 130 | + assert result["removed"] == 2 |
| 131 | + |
| 132 | + |
| 133 | +def test_refresh_keeps_success_records_of_existing_rows(schema_by_backend): |
| 134 | + """A success record stays while its row exists, even if its key leaves key_source.""" |
| 135 | + |
| 136 | + @schema_by_backend |
| 137 | + class Raw(dj.Manual): |
| 138 | + definition = """ |
| 139 | + raw_id : int32 |
| 140 | + --- |
| 141 | + v : float32 |
| 142 | + """ |
| 143 | + |
| 144 | + @schema_by_backend |
| 145 | + class Gated(dj.Computed): |
| 146 | + definition = """ |
| 147 | + -> Raw |
| 148 | + --- |
| 149 | + w : float32 |
| 150 | + """ |
| 151 | + |
| 152 | + @property |
| 153 | + def key_source(self): |
| 154 | + return Raw & "v >= 0" |
| 155 | + |
| 156 | + def make(self, key): |
| 157 | + self.insert1(dict(key, w=2 * (Raw & key).fetch1("v"))) |
| 158 | + |
| 159 | + with dj.config.override(jobs={"keep_completed": True}): |
| 160 | + Raw.insert([dict(raw_id=i, v=float(i)) for i in range(2)]) |
| 161 | + Gated.populate(reserve_jobs=True) |
| 162 | + Raw.update1(dict(raw_id=0, v=-1.0)) # leaves key_source; Gated row remains |
| 163 | + |
| 164 | + Gated.jobs.refresh() |
| 165 | + |
| 166 | + assert _statuses(Gated.jobs) == {0: "success", 1: "success"} |
| 167 | + |
| 168 | + |
| 169 | +def test_stale_timeout_zero_still_skips_stale_check(pipeline): |
| 170 | + """``stale_timeout=0`` keeps skipping the age-based check for pending jobs.""" |
| 171 | + Raw, Proc = pipeline |
| 172 | + Raw.insert([dict(raw_id=i, v=float(i)) for i in range(2)]) |
| 173 | + Proc.jobs.refresh() |
| 174 | + (Raw & {"raw_id": 1}).delete(prompt=False) |
| 175 | + _backdate(Proc.jobs) |
| 176 | + |
| 177 | + Proc.jobs.refresh(stale_timeout=0) |
| 178 | + assert _statuses(Proc.jobs) == {0: "pending", 1: "pending"} |
| 179 | + |
| 180 | + Proc.jobs.refresh() |
| 181 | + assert _statuses(Proc.jobs) == {0: "pending"} |
| 182 | + |
| 183 | + |
| 184 | +def test_refresh_cleanup_is_set_based(pipeline, monkeypatch): |
| 185 | + """Cleanup issues a fixed number of statements, not one per vanished key.""" |
| 186 | + Raw, Proc = pipeline |
| 187 | + n = 20 |
| 188 | + with dj.config.override(jobs={"keep_completed": True}): |
| 189 | + Raw.insert([dict(raw_id=i, v=float(i)) for i in range(n)]) |
| 190 | + Proc.populate(reserve_jobs=True) |
| 191 | + Raw.delete(prompt=False) |
| 192 | + _backdate(Proc.jobs) # also past stale_timeout: both cleanup steps apply |
| 193 | + |
| 194 | + jobs = Proc.jobs |
| 195 | + queries = [] |
| 196 | + query = jobs.connection.query |
| 197 | + |
| 198 | + def counting_query(sql, *args, **kwargs): |
| 199 | + queries.append(sql) |
| 200 | + return query(sql, *args, **kwargs) |
| 201 | + |
| 202 | + monkeypatch.setattr(jobs.connection, "query", counting_query) |
| 203 | + result = jobs.refresh() |
| 204 | + monkeypatch.undo() |
| 205 | + |
| 206 | + assert result["removed"] == n |
| 207 | + assert len(Proc.jobs) == 0 |
| 208 | + deletes = [sql for sql in queries if sql.lstrip().upper().startswith("DELETE")] |
| 209 | + assert 1 <= len(deletes) <= 2 |
| 210 | + assert len(queries) < n |
0 commit comments