:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): reject collab saves when client version is behind (#59677)
Alex Lider3ff4e6e39a7d
diff --git a/products/notebooks/backend/api/notebook.py b/products/notebooks/backend/api/notebook.pyindex b50665f12256..029155c89a6e 100644--- a/products/notebooks/backend/api/notebook.py+++ b/products/notebooks/backend/api/notebook.py@@ -759,6 +759,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDclient_id=data["client_id"],steps_json=data["steps"],last_seen_version=data["version"],+ last_saved_version=notebook.version,user_id=user.pk,user_name=user_name,cursor_head=data.get("cursor_head"),diff --git a/products/notebooks/backend/collab.py b/products/notebooks/backend/collab.pyindex fbfe9a006ba2..cba1d2e140a1 100644--- a/products/notebooks/backend/collab.py+++ b/products/notebooks/backend/collab.py@@ -41,45 +41,58 @@ class StepEntry:class SubmitResult:# "accepted" - steps appended; `version` is the new top# "conflict" - caller is behind; `version` is the current top, `steps_since` is the missed range- # "stale" - missed range was trimmed (MAXLEN/TTL); caller must reload from Postgres+ # "stale" - missed range was trimmed (MAXLEN/TTL) or the stream was lost and the client's+ # baseline no longer matches Postgres; caller must reload from Postgresstatus: Literal["accepted", "conflict", "stale"]version: intsteps_since: list[StepEntry] | None = None-# Atomically append N step entries if the latest stream version equals last_seen_version.-# If the stream is empty we trust the caller's last_seen_version,-# frontend always loads it from Postgres and seed the stream from there.+# Atomically append N step entries if the current stream version equals last_seen_version.+#+# When the stream is empty (TTL expired / evicted / never written) we cannot trust the caller's+# last_seen_version on its own — a stale tab with an old baseline could otherwise be accepted+# and silently downgrade the persisted version on the subsequent Notebook update. Cross-check+# against last_saved_version (the value durably stored in Postgres): only accept if they match+# exactly, otherwise force the client to reload.## ARGV:-# 1: last_seen_version (int)-# 2: ttl_seconds (int)-# 3: max_length (int)-# 4..N: step entry JSON strings (one per prosemirror step)+# 1: last_seen_version (int) -- prosemirror confirmed version on the client+# 2: last_saved_version (int) -- notebook.version from Postgres, fetched by the caller+# 3: ttl_seconds (int)+# 4: max_length (int)+# 5..N: step entry JSON strings (one per prosemirror step)## Returns:-# {0, current_version} -- conflict, caller should fetch missed steps-# {1, new_version} -- accepted+# {0, current_stream_version} -- conflict, caller should fetch missed steps+# {1, new_version} -- accepted+# {2, last_saved_version} -- stream lost + client baseline disagrees with Postgres → stale_APPEND_STEPS_LUA = """local stream_key = KEYS[1]local last_seen_version = tonumber(ARGV[1])-local ttl = tonumber(ARGV[2])-local max_length = tonumber(ARGV[3])+local last_saved_version = tonumber(ARGV[2])+local ttl = tonumber(ARGV[3])+local max_length = tonumber(ARGV[4])-local current_version = last_seen_version+local current_stream_version = last_seen_versionlocal last = redis.call('XREVRANGE', stream_key, '+', '-', 'COUNT', 1)-if #last > 0 then+local stream_empty = (#last == 0)+if not stream_empty thenlocal id_str = last[1][1]local dash = string.find(id_str, '-')- current_version = tonumber(string.sub(id_str, 1, dash - 1))+ current_stream_version = tonumber(string.sub(id_str, 1, dash - 1))+end++if stream_empty and last_seen_version ~= last_saved_version then+ return {2, last_saved_version}end-if current_version ~= last_seen_version then- return {0, current_version}+if current_stream_version ~= last_seen_version then+ return {0, current_stream_version}end-local next_version = current_version-for i = 4, #ARGV do+local next_version = current_stream_version+for i = 5, #ARGV donext_version = next_version + 1redis.call('XADD', stream_key, 'MAXLEN', '~', max_length, next_version .. '-0', 'data', ARGV[i])end@@ -96,6 +109,7 @@ def submit_steps(steps_json: list[dict],last_seen_version: int,*,+ last_saved_version: int,user_id: int | None = None,user_name: str | None = None,cursor_head: int | None = None,@@ -113,18 +127,20 @@ def submit_steps(script = client.register_script(_APPEND_STEPS_LUA)accepted, version = script(keys=[stream_key],- args=[last_seen_version, STREAM_TTL_SECONDS, STREAM_MAX_LENGTH, *serialized],+ args=[last_seen_version, last_saved_version, STREAM_TTL_SECONDS, STREAM_MAX_LENGTH, *serialized],)if accepted == 1:return SubmitResult(status="accepted", version=version)+ if accepted == 2:+ return SubmitResult(status="stale", version=version)- return _fetch_missed_steps(stream_key, last_seen_version=last_seen_version, current_version=version)+ return _fetch_missed_steps(stream_key, last_seen_version=last_seen_version, current_stream_version=version)-def _fetch_missed_steps(stream_key: str, *, last_seen_version: int, current_version: int) -> SubmitResult:+def _fetch_missed_steps(stream_key: str, *, last_seen_version: int, current_stream_version: int) -> SubmitResult:client = redis_module.get_client()- raw = client.xrange(stream_key, min=f"({last_seen_version}-0", max=f"{current_version}-0")+ raw = client.xrange(stream_key, min=f"({last_seen_version}-0", max=f"{current_stream_version}-0")missed_steps: list[StepEntry] = []for _stream_id, fields in raw:@@ -132,11 +148,11 @@ def _fetch_missed_steps(stream_key: str, *, last_seen_version: int, current_versmissed_steps.append(StepEntry(step=data["step"], client_id=data["client_id"]))# MAXLEN/TTL trimmed part of the gap - incomplete rebase set, reload from Postgres- gap_size = current_version - last_seen_version+ gap_size = current_stream_version - last_seen_versionif len(missed_steps) < gap_size:- return SubmitResult(status="stale", version=current_version)+ return SubmitResult(status="stale", version=current_stream_version)- return SubmitResult(status="conflict", version=current_version, steps_since=missed_steps)+ return SubmitResult(status="conflict", version=current_stream_version, steps_since=missed_steps)async def stream_collab_sse(diff --git a/products/notebooks/backend/test/test_collab.py b/products/notebooks/backend/test/test_collab.pyindex 8d29beda7cc5..1d05e31b5517 100644--- a/products/notebooks/backend/test/test_collab.py+++ b/products/notebooks/backend/test/test_collab.py@@ -10,18 +10,46 @@ from products.notebooks.backend.collab import STREAM_KEY_PATTERN, STREAM_MAX_LENclass TestNotebookCollab(BaseTest):def test_submit_to_empty_stream_seeds_position_from_caller(self):# No init endpoint anymore — first writer trusts last_seen_version (loaded from Postgres).- result = submit_steps(self.team.pk, "nb1", "client1", [{"stepType": "replace", "from": 0, "to": 0}], 5)+ result = submit_steps(+ self.team.pk,+ "nb1",+ "client1",+ [{"stepType": "replace", "from": 0, "to": 0}],+ 5,+ last_saved_version=5,+ )assert result.status == "accepted"assert result.version == 6def test_submit_steps_accepted(self):- result = submit_steps(self.team.pk, "nb3", "client1", [{"stepType": "replace", "from": 0, "to": 0}], 0)+ result = submit_steps(+ self.team.pk,+ "nb3",+ "client1",+ [{"stepType": "replace", "from": 0, "to": 0}],+ 0,+ last_saved_version=0,+ )assert result.status == "accepted"assert result.version == 1def test_submit_steps_rejected_on_version_mismatch(self):- submit_steps(self.team.pk, "nb4", "client1", [{"stepType": "replace", "from": 0, "to": 0}], 0)- result = submit_steps(self.team.pk, "nb4", "client2", [{"stepType": "replace", "from": 1, "to": 1}], 0)+ submit_steps(+ self.team.pk,+ "nb4",+ "client1",+ [{"stepType": "replace", "from": 0, "to": 0}],+ 0,+ last_saved_version=0,+ )+ result = submit_steps(+ self.team.pk,+ "nb4",+ "client2",+ [{"stepType": "replace", "from": 1, "to": 1}],+ 0,+ last_saved_version=1,+ )assert result.status == "conflict"assert result.version == 1assert result.steps_since == [@@ -34,7 +62,7 @@ class TestNotebookCollab(BaseTest):{"stepType": "replace", "from": 1, "to": 1},{"stepType": "replace", "from": 2, "to": 2},]- result = submit_steps(self.team.pk, "nb5", "client1", steps, 0)+ result = submit_steps(self.team.pk, "nb5", "client1", steps, 0, last_saved_version=0)assert result.status == "accepted"assert result.version == 3@@ -53,6 +81,7 @@ class TestNotebookCollab(BaseTest):f"client{i}",[{"stepType": "replace", "from": i, "to": i}],expected_version,+ last_saved_version=expected_version,)assert result.status == "accepted"expected_version += 1@@ -60,8 +89,22 @@ class TestNotebookCollab(BaseTest):assert expected_version == num_clientsdef test_submit_steps_returns_stale_when_stream_trimmed(self):- submit_steps(self.team.pk, "nb_trimmed", "client1", [{"stepType": "replace", "from": 0, "to": 0}], 0)- submit_steps(self.team.pk, "nb_trimmed", "client1", [{"stepType": "replace", "from": 1, "to": 1}], 1)+ submit_steps(+ self.team.pk,+ "nb_trimmed",+ "client1",+ [{"stepType": "replace", "from": 0, "to": 0}],+ 0,+ last_saved_version=0,+ )+ submit_steps(+ self.team.pk,+ "nb_trimmed",+ "client1",+ [{"stepType": "replace", "from": 1, "to": 1}],+ 1,+ last_saved_version=1,+ )client = redis.get_client()# Force-trim past version 1 to simulate MAXLEN/TTL eviction; version 2 (id 2-0) survives.@@ -70,11 +113,63 @@ class TestNotebookCollab(BaseTest):minid="2-0",)- result = submit_steps(self.team.pk, "nb_trimmed", "client2", [{"stepType": "replace", "from": 2, "to": 2}], 0)+ result = submit_steps(+ self.team.pk,+ "nb_trimmed",+ "client2",+ [{"stepType": "replace", "from": 2, "to": 2}],+ 0,+ last_saved_version=2,+ )assert result.status == "stale"assert result.version == 2assert result.steps_since is None+ def test_empty_stream_with_stale_client_baseline_returns_stale(self):+ # Stream lost (e.g. TTL expired) — Postgres still has the high version. A stale tab whose+ # baseline doesn't match Postgres must not be accepted; otherwise its save would+ # overwrite Postgres with a lower version. Client must reload from Postgres.+ result = submit_steps(+ self.team.pk,+ "nb_stale_after_expiry",+ "client_stale",+ [{"stepType": "replace", "from": 0, "to": 0}],+ last_seen_version=937,+ last_saved_version=946,+ )+ assert result.status == "stale"+ assert result.version == 946+ assert result.steps_since is None++ def test_empty_stream_with_client_ahead_of_postgres_returns_stale(self):+ # Defensive: even if the client is somehow ahead of Postgres (legacy PATCH path went+ # backwards, Postgres restore, etc.) we still cannot rebase against an empty stream.+ result = submit_steps(+ self.team.pk,+ "nb_client_ahead",+ "client_ahead",+ [{"stepType": "replace", "from": 0, "to": 0}],+ last_seen_version=946,+ last_saved_version=937,+ )+ assert result.status == "stale"+ assert result.version == 937+ assert result.steps_since is None++ def test_empty_stream_with_matching_postgres_accepts(self):+ # The legitimate first save after a Redis flush: client baseline matches Postgres so+ # the empty stream is safely seeded from there.+ result = submit_steps(+ self.team.pk,+ "nb_first_save_after_flush",+ "client1",+ [{"stepType": "replace", "from": 0, "to": 0}],+ last_seen_version=946,+ last_saved_version=946,+ )+ assert result.status == "accepted"+ assert result.version == 947+def test_stream_maxlen_constant_is_sane(self):# Sanity: MAXLEN must comfortably hold an hour of edits. Adjust deliberately if changed.assert STREAM_MAX_LENGTH >= 1000diff --git a/products/notebooks/backend/test/test_collab_api.py b/products/notebooks/backend/test/test_collab_api.pyindex 4cd39676ad42..73a04aa1f107 100644--- a/products/notebooks/backend/test/test_collab_api.py+++ b/products/notebooks/backend/test/test_collab_api.py@@ -328,6 +328,7 @@ class TestNotebookCollabStreamAPI(APIBaseTest):"client-1",[{"stepType": "replace", "from": 0, "to": 0}],notebook["version"],+ last_saved_version=notebook["version"],)# Last-Event-ID=0-0 means "from the beginning of the stream", so the pre-populated@@ -355,6 +356,7 @@ class TestNotebookCollabStreamAPI(APIBaseTest):"client-A",[{"stepType": "replace", "from": 0, "to": 0}],base_version,+ last_saved_version=base_version,)submit_steps(self.team.pk,@@ -362,6 +364,7 @@ class TestNotebookCollabStreamAPI(APIBaseTest):"client-B",[{"stepType": "replace", "from": 1, "to": 1}],base_version + 1,+ last_saved_version=base_version + 1,)first_step_id = f"{base_version + 1}-0"