Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Do not let a sibling deployment's artifact evict a working model

Daoud Clarke2af858917d13
diff --git a/mwmbl/moderation/artifacts/README.md b/mwmbl/moderation/artifacts/README.md
index 3f02901..eedfd3c 100644
--- a/mwmbl/moderation/artifacts/README.md
+++ b/mwmbl/moderation/artifacts/README.md
@@ -58,21 +58,33 @@ and every deploy runs on the deterministic checks alone until the first retrain
probe is what turns that from an exception per domain inside the enrichment task into an honest
"not assessed yet" — it is not a licence to leave the artifact stale.
-## Retrain from the image the workers are running
-
-`is_compatible()` protects the running code from an artifact **older** than it. Nothing can
-protect it from one that is *newer*: a featuriser is pickled whole, so a model trained by code
-with one more feature than the workers build produces a matrix they cannot use, and they have no
-way to know that in advance.
-
-That is not hypothetical. In August 2026 a retrain run through `dokku enter` on a freshly built
-image published a model with nine shape features while the long-running container was still on
-eight. Every one of the 2,409 rows in the queue rescore failed with `X has 57673 features, but
-LogisticRegression is expecting 57674`, and the task retried on the same exception.
-
-So **deploy first, then retrain** — the process that publishes must be running the same image as
-the process that serves. If it happens anyway, delete the offending `ModerationModelArtifact` row
-and the workers fall back to the warm start here; then deploy and retrain again.
+## This table is shared between deployments
+
+`api.mwmbl.org` and `beta.mwmbl.org` point at the same Postgres instance, so they share this
+table — and the `background_task` queue with it. `_published_stamp()` returns the newest row in
+the database, not the newest row *this deployment* published, so whenever the two are running
+different code the newest row is routinely the other one's.
+
+That matters because a featuriser is pickled whole. A model trained by code with one more shape
+feature than a deployment builds produces a matrix that deployment cannot use, and there is no
+way for it to know in advance. In August 2026 a retrain on beta (nine shape features) published
+into the shared table while api was still on `main` (eight); api picked it up on its next refresh
+and every one of the 2,409 rows in the queue rescore failed with `X has 57673 features, but
+LogisticRegression is expecting 57674`, retrying on the same exception. The rescore task is in
+the shared queue too, so it does not even reliably run on the deployment that scheduled it.
+
+Three things now contain this, and none of them is a substitute for the others:
+
+- `is_compatible()` probes an artifact at load and refuses one this code cannot featurise.
+- `get_model()` keeps serving what it has when the newest row is unusable, rather than dropping
+ to a fallback once a minute because a sibling deployment retrained.
+- `suggest()` degrades to UNSURE if a model that loaded still fails to score, so one unusable
+ artifact cannot fail a whole queue rescore.
+
+The standing fix is to stop sharing: either give the deployments separate databases, or scope
+the artifact table per deployment. Until then, **retrain from the deployment whose code is
+oldest**, so what it publishes is usable by both. If a bad row lands anyway, delete it — every
+deployment falls back to the warm start here.
## What this version was trained on
diff --git a/mwmbl/moderation/model.py b/mwmbl/moderation/model.py
index cc596ba..dccd9d1 100644
--- a/mwmbl/moderation/model.py
+++ b/mwmbl/moderation/model.py
@@ -203,6 +203,14 @@ def get_model() -> Optional[ModerationModel]:
None (until the published artifact changes) when nothing can be loaded, so a suggestion
falls back to the deterministic checks rather than failing.
+
+ **A newer artifact this code cannot use does not evict the one it is serving.** The
+ artifact table is a single row set shared by every deployment pointed at the database -
+ api and beta share a Postgres instance - so the newest row is routinely the *other*
+ deployment's, trained by code with a different feature set. Replacing a working model with
+ a fallback once a minute because a sibling app retrained is worse than ignoring the row:
+ the stamp is recorded either way, so a rejected artifact is unpickled once rather than on
+ every refresh.
"""
global _model, _loaded_stamp, _checked_at
with _lock:
@@ -210,7 +218,16 @@ def get_model() -> Optional[ModerationModel]:
return _model
published = _published_stamp()
if _checked_at is None or published != _loaded_stamp:
- _model = _load(published[0] if published else None)
+ candidate = _load(published[0] if published else None)
+ if candidate is not None:
+ _model = candidate
+ elif _model is None:
+ _model = _load_bundled()
+ else:
+ logger.warning(
+ "Published artifact %s is not usable by this code; continuing to serve %s. "
+ "This is what a sibling deployment retraining against the same database "
+ "looks like.", published[0] if published else "(none)", _model.version)
_loaded_stamp = published
_checked_at = time.monotonic()
return _model
diff --git a/test/test_domain_moderation.py b/test/test_domain_moderation.py
index 84a42c0..e66a82f 100644
--- a/test/test_domain_moderation.py
+++ b/test/test_domain_moderation.py
@@ -1441,6 +1441,45 @@ def test_a_decisive_check_still_wins_over_a_model_that_cannot_score():
assert suggestion.reason_source == "rule"
+def test_a_sibling_deployments_artifact_does_not_evict_a_working_model(monkeypatch):
+ """api and beta share a Postgres instance, so they share this table. The newest row is
+ routinely the other deployment's, trained by code with a different feature set - and
+ swapping a working model for a fallback once a minute because a sibling retrained is worse
+ than ignoring the row."""
+ publish(_StubModel("domain-mod-2026-09-01"), {})
+ assert get_model().version == "domain-mod-2026-09-01"
+
+ monkeypatch.setattr(model_module, "MODEL_REFRESH_SECONDS", 0)
+ ModerationModelArtifact.objects.create(
+ version="from-the-other-app", metrics={},
+ model=artifact_bytes(_StaleFeatureSetModel()))
+
+ assert get_model().version == "domain-mod-2026-09-01"
+
+
+def test_an_unusable_artifact_is_not_unpickled_on_every_refresh(monkeypatch):
+ """The rejection is remembered by stamp, so a sibling app's model costs one load rather
+ than one per minute for as long as it stays the newest row."""
+ publish(_StubModel("domain-mod-2026-09-01"), {})
+ get_model()
+
+ monkeypatch.setattr(model_module, "MODEL_REFRESH_SECONDS", 0)
+ ModerationModelArtifact.objects.create(
+ version="from-the-other-app", metrics={},
+ model=artifact_bytes(_StaleFeatureSetModel()))
+
+ loads = []
+ original = model_module._load
+ monkeypatch.setattr(model_module, "_load",
+ lambda version: loads.append(version) or original(version))
+
+ for _ in range(3):
+ assert get_model().version == "domain-mod-2026-09-01"
+ assert loads == ["from-the-other-app"]
+
+
# --------------------------------------------------------------------- request validation
@pytest.mark.django_db