Skip to content

Commit 62aa276

Browse files
rustyconoverclaude
andcommitted
storage: add state_append + state_log_scan to all backends (Step 2)
Adds the append-only verb to the unified state_* API. The function_state_log table was provisioned in Turn 1, so this is just glue: * FunctionStorage Protocol — two new methods * BoundStorage facade — convenience wrappers (state_append / state_log_scan) * FunctionStorageSqlite — INSERT OR IGNORE on UNIQUE(scope, ns, key, attempt_id) for replay; SELECT-back to recover the prior id on conflict since SQLite's lastrowid is unreliable after IGNORE. * FunctionStorageAzureSql — SELECT-then-INSERT...OUTPUT inserted.id; the unique index idx_function_state_log_replay enforces idempotency. * FunctionStorageCfDo — POST /state_append and /state_log_scan with attempt_id splicing on the append (HTTP-retry replay-detection). Tests: 9 SQLite cases (round-trip, monotone ordinals, key/ns/scope isolation, non-destructive scan, empty scan, execution_clear wipes the log, BoundStorage facade); 2 mock cases each for Azure SQL and CfDo (replay-hit-returns-prior-ordinal, scan SQL/HTTP shape). All pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 5963d58 commit 62aa276

6 files changed

Lines changed: 367 additions & 5 deletions

‎tests/test_function_storage.py‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,3 +241,76 @@ def test_facade_pack_int_key(self) -> None:
241241
packed = BoundStorage.pack_int_key(n)
242242
assert len(packed) == 8
243243
assert int.from_bytes(packed, "little", signed=True) == n
244+
245+
# --- state_append / state_log_scan (append-only log) ---
246+
247+
def test_state_append_then_log_scan_single_key(self, storage: FunctionStorageSqlite) -> None:
248+
"""Appended values come back in append order via state_log_scan."""
249+
scope = b"exec-log"
250+
storage.state_append(scope, b"buf", b"k", b"a")
251+
storage.state_append(scope, b"buf", b"k", b"b")
252+
storage.state_append(scope, b"buf", b"k", b"c")
253+
assert storage.state_log_scan(scope, b"buf", b"k") == [b"a", b"b", b"c"]
254+
255+
def test_state_append_returns_monotone_ordinals_per_key(self, storage: FunctionStorageSqlite) -> None:
256+
"""Per-key ordinals strictly increase across appends."""
257+
scope = b"exec-log"
258+
ord1 = storage.state_append(scope, b"buf", b"k", b"a")
259+
ord2 = storage.state_append(scope, b"buf", b"k", b"b")
260+
ord3 = storage.state_append(scope, b"buf", b"k", b"c")
261+
assert ord1 < ord2 < ord3
262+
263+
def test_state_log_scan_isolates_keys(self, storage: FunctionStorageSqlite) -> None:
264+
"""Logs for distinct keys in the same namespace stay separate."""
265+
scope = b"exec-log"
266+
storage.state_append(scope, b"buf", b"k1", b"a")
267+
storage.state_append(scope, b"buf", b"k2", b"x")
268+
storage.state_append(scope, b"buf", b"k1", b"b")
269+
assert storage.state_log_scan(scope, b"buf", b"k1") == [b"a", b"b"]
270+
assert storage.state_log_scan(scope, b"buf", b"k2") == [b"x"]
271+
272+
def test_state_log_scan_isolates_namespaces(self, storage: FunctionStorageSqlite) -> None:
273+
"""Logs for the same key in different namespaces stay separate."""
274+
scope = b"exec-log"
275+
storage.state_append(scope, b"ns-a", b"k", b"a1")
276+
storage.state_append(scope, b"ns-b", b"k", b"b1")
277+
assert storage.state_log_scan(scope, b"ns-a", b"k") == [b"a1"]
278+
assert storage.state_log_scan(scope, b"ns-b", b"k") == [b"b1"]
279+
280+
def test_state_log_scan_isolates_scopes(self, storage: FunctionStorageSqlite) -> None:
281+
"""Logs for the same key in different scopes stay separate."""
282+
storage.state_append(b"exec-A", b"buf", b"k", b"a")
283+
storage.state_append(b"exec-B", b"buf", b"k", b"b")
284+
assert storage.state_log_scan(b"exec-A", b"buf", b"k") == [b"a"]
285+
assert storage.state_log_scan(b"exec-B", b"buf", b"k") == [b"b"]
286+
287+
def test_state_log_scan_is_non_destructive(self, storage: FunctionStorageSqlite) -> None:
288+
"""Repeated scans return the same data."""
289+
scope = b"exec-log"
290+
storage.state_append(scope, b"buf", b"k", b"a")
291+
storage.state_append(scope, b"buf", b"k", b"b")
292+
first = storage.state_log_scan(scope, b"buf", b"k")
293+
second = storage.state_log_scan(scope, b"buf", b"k")
294+
assert first == second == [b"a", b"b"]
295+
296+
def test_state_log_scan_empty_returns_empty(self, storage: FunctionStorageSqlite) -> None:
297+
"""Scan of a (scope, ns, key) that was never appended returns []."""
298+
assert storage.state_log_scan(b"exec-x", b"buf", b"k") == []
299+
300+
def test_execution_clear_wipes_log(self, storage: FunctionStorageSqlite) -> None:
301+
"""execution_clear removes function_state_log rows for the scope."""
302+
scope = b"exec-log"
303+
storage.state_append(scope, b"buf", b"k", b"a")
304+
storage.state_append(scope, b"buf", b"k", b"b")
305+
storage.execution_clear(scope)
306+
assert storage.state_log_scan(scope, b"buf", b"k") == []
307+
308+
def test_facade_state_append_log_scan_roundtrip(self, storage: FunctionStorageSqlite) -> None:
309+
"""BoundStorage.state_append / state_log_scan wrappers work."""
310+
from vgi.function_storage import BoundStorage
311+
312+
bs = BoundStorage(storage, b"exec-log", attach_opaque_data=b"a")
313+
ord1 = bs.state_append(b"buf", b"k", b"a")
314+
ord2 = bs.state_append(b"buf", b"k", b"b")
315+
assert ord1 < ord2
316+
assert bs.state_log_scan(b"buf", b"k") == [b"a", b"b"]

‎tests/test_function_storage_azure_sql.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,3 +403,27 @@ def test_execution_clear_wipes_both_tables(
403403
assert any("DELETE FROM function_state " in s for s in sqls)
404404
assert any("DELETE FROM function_state_log " in s for s in sqls)
405405

406+
def test_state_append_replay_returns_prior_ordinal(
407+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
408+
) -> None:
409+
"""state_append: replay-detection SELECT hit returns prior ordinal — no INSERT."""
410+
mock_cursor.set_results([(42,)]) # replay-detection SELECT finds prior id=42
411+
ordinal = storage.state_append(b"exec1", b"buf", b"k", b"item")
412+
assert ordinal == 42
413+
sqls = [s for s, _ in mock_cursor.executed]
414+
# Only the replay-detection SELECT should have run; no INSERT.
415+
assert any("SELECT id FROM function_state_log" in s for s in sqls)
416+
assert not any("INSERT INTO function_state_log" in s for s in sqls)
417+
418+
def test_state_log_scan_emits_select_in_id_order(
419+
self, storage: FunctionStorageAzureSql, mock_cursor: _MockCursor,
420+
) -> None:
421+
"""state_log_scan SELECTs values for (scope, ns, key) ORDER BY id."""
422+
mock_cursor.set_results([(b"a",), (b"b",), (b"c",)])
423+
result = storage.state_log_scan(b"exec1", b"buf", b"k")
424+
assert result == [b"a", b"b", b"c"]
425+
sql, params = mock_cursor.executed[0]
426+
assert "SELECT value FROM function_state_log" in sql
427+
assert "ORDER BY id" in sql
428+
assert params == (b"exec1", b"buf", b"k")
429+

‎tests/test_function_storage_cf_do.py‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,4 +297,30 @@ def test_execution_clear_returns_count(
297297
assert n == 8
298298
body = _body(mock_transport.requests[0])
299299
assert body["scope_id"] == _b64(b"exec1")
300-
assert "attempt_id" in body # naturally idempotent but audited
300+
301+
def test_state_append_carries_attempt_id_returns_ordinal(
302+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
303+
) -> None:
304+
"""state_append sends scope/ns/key/item + attempt_id, returns ordinal."""
305+
mock_transport.queue_response(200, {"ordinal": 17})
306+
ordinal = storage.state_append(b"exec1", b"buf", b"k1", b"payload")
307+
assert ordinal == 17
308+
body = _body(mock_transport.requests[0])
309+
assert body["scope_id"] == _b64(b"exec1")
310+
assert body["ns"] == _b64(b"buf")
311+
assert body["key"] == _b64(b"k1")
312+
assert body["item"] == _b64(b"payload")
313+
assert "attempt_id" in body
314+
315+
def test_state_log_scan_no_attempt_id_returns_values(
316+
self, storage: FunctionStorageCfDo, mock_transport: _MockTransport,
317+
) -> None:
318+
"""state_log_scan is read-only — no attempt_id; values returned in order."""
319+
mock_transport.queue_response(200, {"values": [_b64(b"a"), _b64(b"b"), _b64(b"c")]})
320+
result = storage.state_log_scan(b"exec1", b"buf", b"k1")
321+
assert result == [b"a", b"b", b"c"]
322+
body = _body(mock_transport.requests[0])
323+
assert body["scope_id"] == _b64(b"exec1")
324+
assert body["ns"] == _b64(b"buf")
325+
assert body["key"] == _b64(b"k1")
326+
assert "attempt_id" not in body

‎vgi/function_storage.py‎

Lines changed: 112 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -340,10 +340,48 @@ def execution_clear(
340340
Naturally idempotent. Returns total row count deleted across both
341341
``function_state`` and ``function_state_log`` tables.
342342

343-
Does NOT touch ``queue_*`` rows or any of the legacy
344-
``worker_state`` / ``stream_state`` / ``aggregate_state`` /
345-
``aggregate_window_partition`` tables that still exist during the
346-
cohabitation window — see the plan file for migration phasing.
343+
Does NOT touch ``queue_*`` rows.
344+
"""
345+
...
346+
347+
# --- Append-only log ---
348+
349+
def state_append(
350+
self,
351+
scope_id: bytes,
352+
ns: bytes,
353+
key: bytes,
354+
item: bytes,
355+
*,
356+
shard_key: str = "",
357+
) -> int:
358+
"""Append ``item`` to the log keyed by (scope_id, ns, key); return ordinal.
359+
360+
Ordinals are globally monotonic across all (scope, ns, key) triples
361+
on a given backend (one IDENTITY/AUTOINCREMENT column for the table).
362+
Per-key order is recovered via the ``(scope_id, ns, key, id)`` index;
363+
``state_log_scan`` yields rows in id order, which corresponds to
364+
append order. Concurrent appenders to the *same* key get distinct
365+
ordinals but interleaving is undefined.
366+
367+
Idempotent on retry: if an earlier attempt with the same
368+
backend-internal ``attempt_id`` already inserted a row, returns the
369+
prior ordinal without re-inserting.
370+
"""
371+
...
372+
373+
def state_log_scan(
374+
self,
375+
scope_id: bytes,
376+
ns: bytes,
377+
key: bytes,
378+
*,
379+
shard_key: str = "",
380+
) -> list[bytes]:
381+
"""Yield all values appended to (scope_id, ns, key) in ordinal order.
382+
383+
Non-destructive. Repeat calls return identical results until
384+
``execution_clear`` wipes the log rows.
347385
"""
348386
...
349387

@@ -563,6 +601,18 @@ def execution_clear(self) -> int:
563601
self._execution_id, shard_key=self._shard_key
564602
)
565603

604+
def state_append(self, ns: bytes, key: bytes, item: bytes) -> int:
605+
"""Append an item to the (ns, key) log; return the assigned ordinal."""
606+
return self._base.state_append(
607+
self._execution_id, ns, key, item, shard_key=self._shard_key
608+
)
609+
610+
def state_log_scan(self, ns: bytes, key: bytes) -> list[bytes]:
611+
"""Yield all values appended to (ns, key) in ordinal order."""
612+
return self._base.state_log_scan(
613+
self._execution_id, ns, key, shard_key=self._shard_key
614+
)
615+
566616
@staticmethod
567617
def pack_int_key(i: int) -> bytes:
568618
"""Sugar: encode an int as 8-byte little-endian for use as ``state_*`` key.
@@ -1040,6 +1090,64 @@ def execution_clear(
10401090
conn.commit()
10411091
return int(c1.rowcount) + int(c2.rowcount)
10421092

1093+
def state_append(
1094+
self,
1095+
scope_id: bytes,
1096+
ns: bytes,
1097+
key: bytes,
1098+
item: bytes,
1099+
*,
1100+
shard_key: str = "",
1101+
) -> int:
1102+
"""Append item; return ordinal. Replay returns prior ordinal via UNIQUE."""
1103+
del shard_key
1104+
import uuid
1105+
1106+
attempt_id = uuid.uuid4().bytes
1107+
conn = self._conn()
1108+
# INSERT OR IGNORE on the UNIQUE(scope, ns, key, attempt_id) index
1109+
# is the replay primitive. On conflict the row already exists from a
1110+
# prior call with this attempt_id; cur.lastrowid is unreliable in
1111+
# that case (SQLite returns 0), so we always SELECT back by attempt_id.
1112+
conn.execute(
1113+
"""
1114+
INSERT OR IGNORE INTO function_state_log
1115+
(scope_id, ns, key, value, attempt_id)
1116+
VALUES (?, ?, ?, ?, ?)
1117+
""",
1118+
(scope_id, ns, key, item, attempt_id),
1119+
)
1120+
conn.commit()
1121+
row = conn.execute(
1122+
"""
1123+
SELECT id FROM function_state_log
1124+
WHERE scope_id = ? AND ns = ? AND key = ? AND attempt_id = ?
1125+
""",
1126+
(scope_id, ns, key, attempt_id),
1127+
).fetchone()
1128+
return int(row[0])
1129+
1130+
def state_log_scan(
1131+
self,
1132+
scope_id: bytes,
1133+
ns: bytes,
1134+
key: bytes,
1135+
*,
1136+
shard_key: str = "",
1137+
) -> list[bytes]:
1138+
"""Yield all values for (scope_id, ns, key) in ordinal order."""
1139+
del shard_key
1140+
conn = self._conn()
1141+
rows = conn.execute(
1142+
"""
1143+
SELECT value FROM function_state_log
1144+
WHERE scope_id = ? AND ns = ? AND key = ?
1145+
ORDER BY id
1146+
""",
1147+
(scope_id, ns, key),
1148+
).fetchall()
1149+
return [bytes(v) for (v,) in rows]
1150+
10431151
# --- Maintenance (not part of protocol) ---
10441152

10451153
def cleanup_old_entries(self, max_age_days: float = 1.0) -> int:

‎vgi/function_storage_azure_sql.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,76 @@ def _do(conn: pymssql.Connection) -> int:
620620

621621
return self._execute_with_retry(_do)
622622

623+
def state_append(
624+
self,
625+
scope_id: bytes,
626+
ns: bytes,
627+
key: bytes,
628+
item: bytes,
629+
*,
630+
shard_key: str = "",
631+
) -> int:
632+
"""Append item; return assigned ordinal. Replay returns prior ordinal."""
633+
del shard_key
634+
import uuid
635+
636+
attempt_id = uuid.uuid4().bytes
637+
638+
def _do(conn: pymssql.Connection) -> int:
639+
cursor = conn.cursor()
640+
# Replay-detection via idx_function_state_log_replay UNIQUE
641+
# (scope_id, ns, key, attempt_id). Look up first; if a prior
642+
# call with this attempt_id already inserted, return its id.
643+
cursor.execute(
644+
"""
645+
SELECT id FROM function_state_log
646+
WHERE scope_id = %s AND ns = %s AND [key] = %s AND attempt_id = %s
647+
""",
648+
(scope_id, ns, key, attempt_id),
649+
)
650+
row = cursor.fetchone()
651+
if row is not None:
652+
return int(row[0])
653+
cursor.execute(
654+
"""
655+
INSERT INTO function_state_log
656+
(scope_id, ns, [key], value, attempt_id)
657+
OUTPUT inserted.id
658+
VALUES (%s, %s, %s, %s, %s)
659+
""",
660+
(scope_id, ns, key, item, attempt_id),
661+
)
662+
new_id = int(cursor.fetchone()[0])
663+
conn.commit()
664+
return new_id
665+
666+
return self._execute_with_retry(_do)
667+
668+
def state_log_scan(
669+
self,
670+
scope_id: bytes,
671+
ns: bytes,
672+
key: bytes,
673+
*,
674+
shard_key: str = "",
675+
) -> list[bytes]:
676+
"""Yield all values for (scope_id, ns, key) in ordinal order."""
677+
del shard_key
678+
679+
def _do(conn: pymssql.Connection) -> list[bytes]:
680+
cursor = conn.cursor()
681+
cursor.execute(
682+
"""
683+
SELECT value FROM function_state_log
684+
WHERE scope_id = %s AND ns = %s AND [key] = %s
685+
ORDER BY id
686+
""",
687+
(scope_id, ns, key),
688+
)
689+
return [bytes(v) for (v,) in cursor.fetchall()]
690+
691+
return self._execute_with_retry(_do)
692+
623693
# --- Factory ---
624694

625695
@classmethod

0 commit comments

Comments
 (0)