Skip to content

Commit 58d19ac

Browse files
rustyconoverclaude
andcommitted
storage: add unified state_* to Azure SQL + CfDo client (Turn 4 part 1/2)
Both cloud backends now implement the unified state_* API alongside the legacy methods. Cloudflare DO server changes ship in a separate commit in vgi-cloudflare-durable-object-storage. Azure SQL (FunctionStorageAzureSql): - New tables: function_state(scope_id, ns, key, value, last_attempt_id, drained_at/drained_by_attempt) and function_state_log(id IDENTITY, scope_id, ns, key, value, attempt_id) with UNIQUE constraint for state_append replay-detection. - Six new methods: state_get_many, state_put_many (T-SQL MERGE), state_scan, state_drain (UPDATE..OUTPUT for atomic tombstone-and- read-back), state_delete, execution_clear. - cleanup_old_entries now sweeps function_state and function_state_log past the retention horizon. - Legacy aggregate_state_* / transaction_state_* / aggregate_window_* stubs now raise with a migration-hint message pointing at state_*. They were already NotImplementedError; this just updates the message. CfDo client (FunctionStorageCfDo): - Six new methods POSTing to /state_get_many, /state_put_many, /state_scan, /state_drain, /state_delete, /execution_clear. - attempt_id generated client-side per call and spliced into the body before the existing _post() retry loop — same pattern as the legacy aggregate_state_put. Read-only methods (state_get_many, state_scan) omit attempt_id since there's nothing to replay-detect. Tests: - 9 new Azure SQL unit tests covering put/get/scan/drain/delete/clear, replay-detection (silent no-op on second put with same attempt_id), legacy method migration-hint message. - 8 new CfDo HTTP-mock tests covering the same surface plus body-shape assertions (attempt_id present on mutating methods, absent on reads). - test_cleanup_old_entries on Azure SQL updated to expect 5 DELETEs (was 3) reflecting the new state tables. Verification: 118 vgi-python storage tests pass (8 new on Azure SQL, 8 new on CfDo, 1 cleanup test updated, 99 existing). 152 vgi C++ subprocess integration tests pass. 83 HTTP test cases pass. The DO server (separate repo) still uses the legacy endpoints — Turn 4 part 2/2 lands its state_* handlers next. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 3d56cf3 commit 58d19ac

4 files changed

Lines changed: 701 additions & 36 deletions

File tree

‎tests/test_function_storage_azure_sql.py‎

Lines changed: 117 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -235,16 +235,18 @@ def test_queue_clear_empty_queue(self, storage: FunctionStorageAzureSql, mock_cu
235235
# --- Cleanup Tests ---
236236

237237
def test_cleanup_old_entries(self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor) -> None:
238-
"""Test cleanup runs DELETE on all three tables."""
238+
"""Test cleanup runs DELETE on every state-bearing table."""
239239
mock_cursor.rowcount = 0
240240
deleted = storage.cleanup_old_entries(max_age_days=1.0)
241241
assert deleted >= 0
242242

243-
# Verify all three tables were cleaned
243+
# Verify every state-bearing table was cleaned: legacy three plus
244+
# the unified state_* pair.
244245
delete_calls = [sql for sql, _ in mock_cursor.executed if "DELETE FROM" in sql]
245-
assert len(delete_calls) == 3
246+
assert len(delete_calls) == 5
246247
tables = {sql.split("DELETE FROM ")[1].split(" ")[0] for sql, _ in mock_cursor.executed if "DELETE FROM" in sql}
247-
assert tables == {"worker_state", "work_queue", "invocation_registry"}
248+
assert tables == {"worker_state", "work_queue", "invocation_registry",
249+
"function_state", "function_state_log"}
248250

249251
# --- Factory Tests ---
250252

@@ -344,3 +346,114 @@ def compute(self) -> None:
344346
pass
345347

346348
assert MyFunction.storage is mock_storage
349+
350+
351+
class TestFunctionStorageAzureSqlStateUnified:
352+
"""Tests for the unified state_* API on the Azure SQL backend."""
353+
354+
@pytest.fixture
355+
def mock_cursor(self) -> _MockCursor:
356+
"""Fresh mock cursor per test."""
357+
return _MockCursor()
358+
359+
@pytest.fixture
360+
def storage(self, mock_cursor: _MockCursor) -> FunctionStorageAzureSql:
361+
"""Storage instance with mocked pymssql.connect."""
362+
mock_conn = _MockConnection(mock_cursor)
363+
s = FunctionStorageAzureSql(
364+
server="t.example", database="db", user="u", password="p",
365+
)
366+
s._connect = lambda: mock_conn # type: ignore[assignment,return-value]
367+
return s
368+
369+
def test_state_get_many_emits_in_clause(
370+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
371+
) -> None:
372+
"""state_get_many issues an IN-clause SELECT against function_state."""
373+
mock_cursor.set_results([(b"k1", b"v1"), (b"k2", b"v2")])
374+
result = storage.state_get_many(b"exec1", b"agg", [b"k1", b"k2", b"miss"])
375+
assert result == [b"v1", b"v2", None]
376+
sql, params = mock_cursor.executed[0]
377+
assert "function_state" in sql
378+
assert "drained_at IS NULL" in sql
379+
assert params[:2] == (b"exec1", b"agg")
380+
assert b"k1" in params and b"k2" in params and b"miss" in params
381+
382+
def test_state_get_many_empty_keys_no_sql(
383+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
384+
) -> None:
385+
"""Empty key list short-circuits without touching SQL."""
386+
result = storage.state_get_many(b"exec1", b"agg", [])
387+
assert result == []
388+
assert mock_cursor.executed == []
389+
390+
def test_state_put_many_uses_merge(
391+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
392+
) -> None:
393+
"""state_put_many issues one MERGE statement per item."""
394+
mock_cursor.set_results([]) # replay-detection SELECT misses → fresh write
395+
storage.state_put_many(b"exec1", b"agg", [(b"k1", b"v1"), (b"k2", b"v2")])
396+
merge_sqls = [s for s, _ in mock_cursor.executed if "MERGE function_state" in s]
397+
assert len(merge_sqls) == 2 # one MERGE per item
398+
399+
def test_state_put_many_replay_silent_no_op(
400+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
401+
) -> None:
402+
"""A replay (first item already present with our attempt_id) is silent."""
403+
mock_cursor.set_results([(1,)])
404+
storage.state_put_many(b"exec1", b"agg", [(b"k1", b"v1"), (b"k2", b"v2")])
405+
merge_sqls = [s for s, _ in mock_cursor.executed if "MERGE function_state" in s]
406+
assert merge_sqls == [] # nothing written
407+
408+
def test_state_drain_emits_update_with_output(
409+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
410+
) -> None:
411+
"""state_drain uses UPDATE..OUTPUT for atomic tombstone-and-read-back."""
412+
mock_cursor.set_results([]) # replay miss
413+
result = storage.state_drain(b"exec1", b"agg")
414+
assert result == []
415+
update_sqls = [s for s, _ in mock_cursor.executed if "UPDATE function_state" in s]
416+
assert len(update_sqls) == 1
417+
assert "OUTPUT inserted." in update_sqls[0]
418+
assert "drained_by_attempt" in update_sqls[0]
419+
420+
def test_state_delete_specific_keys(
421+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
422+
) -> None:
423+
"""state_delete with a key list emits an IN-clause DELETE."""
424+
mock_cursor.rowcount = 2
425+
deleted = storage.state_delete(b"exec1", b"agg", [b"k1", b"k2"])
426+
assert deleted == 2
427+
sql, params = mock_cursor.executed[0]
428+
assert "DELETE FROM function_state" in sql
429+
assert b"k1" in params and b"k2" in params
430+
431+
def test_state_delete_namespace(
432+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
433+
) -> None:
434+
"""state_delete with keys=None wipes the whole namespace."""
435+
mock_cursor.rowcount = 7
436+
deleted = storage.state_delete(b"exec1", b"agg", None)
437+
assert deleted == 7
438+
sql, params = mock_cursor.executed[0]
439+
assert sql == "DELETE FROM function_state WHERE scope_id = %s AND ns = %s"
440+
assert params == (b"exec1", b"agg")
441+
442+
def test_execution_clear_wipes_both_tables(
443+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
444+
) -> None:
445+
"""execution_clear deletes from both function_state and function_state_log."""
446+
mock_cursor.rowcount = 3
447+
deleted = storage.execution_clear(b"exec1")
448+
# Two DELETEs, each reports rowcount 3 → 6 total.
449+
assert deleted == 6
450+
sqls = [s for s, _ in mock_cursor.executed]
451+
assert any("DELETE FROM function_state " in s for s in sqls)
452+
assert any("DELETE FROM function_state_log " in s for s in sqls)
453+
454+
def test_legacy_aggregate_state_get_now_raises_with_migration_hint(
455+
self, storage: FunctionStorageAzureSql,
456+
) -> None:
457+
"""Legacy aggregate_state_get raises with a clear migration message."""
458+
with pytest.raises(NotImplementedError, match="state_get_many"):
459+
storage.aggregate_state_get(b"e", [1, 2])

‎tests/test_function_storage_cf_do.py‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,3 +727,104 @@ def test_cloudflare_do_backend(self) -> None:
727727
with patch.dict("os.environ", env):
728728
s = _resolve_storage()
729729
assert isinstance(s, FunctionStorageCfDo)
730+
731+
732+
class TestCfDoStateUnified:
733+
"""Tests for the unified state_* HTTP client."""
734+
735+
def test_state_get_many_emits_keys(
736+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
737+
) -> None:
738+
"""state_get_many POSTs scope_id/ns/keys, returns parallel value list."""
739+
mock_transport.queue_response(200, {"rows": [
740+
{"value": _b64(b"v1")},
741+
None,
742+
{"value": _b64(b"v3")},
743+
]})
744+
result = storage.state_get_many(b"exec1", b"agg", [b"k1", b"k2", b"k3"])
745+
assert result == [b"v1", None, b"v3"]
746+
body = _body(mock_transport.requests[0])
747+
assert body["scope_id"] == _b64(b"exec1")
748+
assert body["ns"] == _b64(b"agg")
749+
assert body["keys"] == [_b64(b"k1"), _b64(b"k2"), _b64(b"k3")]
750+
assert "attempt_id" not in body # read-only — no replay-detection needed
751+
752+
def test_state_get_many_empty_keys_no_request(
753+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
754+
) -> None:
755+
"""Empty key list short-circuits — no HTTP."""
756+
result = storage.state_get_many(b"exec1", b"agg", [])
757+
assert result == []
758+
assert mock_transport.requests == []
759+
760+
def test_state_put_many_carries_attempt_id(
761+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
762+
) -> None:
763+
"""state_put_many sends items + attempt_id (replay-detection)."""
764+
mock_transport.queue_response(200, {})
765+
storage.state_put_many(b"exec1", b"agg", [(b"k1", b"v1"), (b"k2", b"v2")])
766+
body = _body(mock_transport.requests[0])
767+
assert body["scope_id"] == _b64(b"exec1")
768+
assert body["ns"] == _b64(b"agg")
769+
assert body["items"] == [
770+
{"key": _b64(b"k1"), "value": _b64(b"v1")},
771+
{"key": _b64(b"k2"), "value": _b64(b"v2")},
772+
]
773+
assert "attempt_id" in body
774+
assert len(body["attempt_id"]) == 32 # uuid.uuid4().hex
775+
776+
def test_state_scan_no_attempt_id(
777+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
778+
) -> None:
779+
"""state_scan is read-only — no attempt_id."""
780+
mock_transport.queue_response(200, {"rows": [
781+
{"key": _b64(b"k"), "value": _b64(b"v")},
782+
]})
783+
result = storage.state_scan(b"exec1", b"agg")
784+
assert result == [(b"k", b"v")]
785+
body = _body(mock_transport.requests[0])
786+
assert "attempt_id" not in body
787+
788+
def test_state_drain_carries_attempt_id_for_read_back_replay(
789+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
790+
) -> None:
791+
"""state_drain sends attempt_id (read-back replay on retry)."""
792+
mock_transport.queue_response(200, {"rows": [
793+
{"key": _b64(b"k1"), "value": _b64(b"v1")},
794+
{"key": _b64(b"k2"), "value": _b64(b"v2")},
795+
]})
796+
result = storage.state_drain(b"exec1", b"agg")
797+
assert sorted(result) == [(b"k1", b"v1"), (b"k2", b"v2")]
798+
body = _body(mock_transport.requests[0])
799+
assert "attempt_id" in body
800+
801+
def test_state_delete_with_keys(
802+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
803+
) -> None:
804+
"""state_delete with key list sends keys + returns count."""
805+
mock_transport.queue_response(200, {"deleted": 2})
806+
n = storage.state_delete(b"exec1", b"agg", [b"k1", b"k2"])
807+
assert n == 2
808+
body = _body(mock_transport.requests[0])
809+
assert body["keys"] == [_b64(b"k1"), _b64(b"k2")]
810+
811+
def test_state_delete_namespace_no_keys_field(
812+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
813+
) -> None:
814+
"""state_delete with keys=None omits the keys field — server interprets as wipe-namespace."""
815+
mock_transport.queue_response(200, {"deleted": 5})
816+
n = storage.state_delete(b"exec1", b"agg", None)
817+
assert n == 5
818+
body = _body(mock_transport.requests[0])
819+
assert "keys" not in body
820+
821+
def test_execution_clear_returns_count(
822+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
823+
) -> None:
824+
"""execution_clear sends scope_id, returns total deleted across both tables."""
825+
mock_transport.queue_response(200, {"deleted": 8})
826+
n = storage.execution_clear(b"exec1")
827+
assert n == 8
828+
body = _body(mock_transport.requests[0])
829+
assert body["scope_id"] == _b64(b"exec1")
830+
assert "attempt_id" in body # naturally idempotent but audited

0 commit comments

Comments
 (0)