Fix cached session identity and document PR 63 regression checks

This commit is contained in:
2026-10-24 08:34:58 +03:00
parent 35f252ee4f
commit 6038c0f375
11 changed files with 700 additions and 277 deletions
+10 -10
View File
@@ -18,13 +18,9 @@ def main() -> None:
cur.execute("INSERT INTO chat_members(chat_id, user_id) VALUES (%s, %s)", (chat_id, user_id))
for idx in range(10000):
cur.execute(
"INSERT INTO messages(id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, NOW() - INTERVAL '%s milliseconds')",
"INSERT INTO messages(id, chat_id, sender_id, text, created_at) VALUES (%s, %s, %s, %s, NOW() - %s * INTERVAL '1 millisecond')",
(uuid.uuid4(), chat_id, user_id, f"msg-{idx}", idx),
)
conn.commit()
cursor_ts = "2100-01-01T00:00:00Z"
cursor_id = str(uuid.uuid4())
explain_sql = """
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
@@ -32,12 +28,16 @@ def main() -> None:
WHERE chat_id = %s
AND (created_at, id) > (%s::timestamptz, %s::uuid)
ORDER BY created_at ASC, id ASC
LIMIT 1
LIMIT 51
"""
cur.execute(explain_sql, (chat_id, cursor_ts, cursor_id))
plan = cur.fetchall()
print("\n".join(row[0] for row in plan))
for offset in (0, 5000, 9900):
cur.execute("SELECT created_at, id FROM messages WHERE chat_id = %s ORDER BY created_at, id OFFSET %s LIMIT 1", (chat_id, offset))
cursor_ts, cursor_id = cur.fetchone()
cur.execute(explain_sql, (chat_id, cursor_ts, cursor_id))
print(f"Page after position {offset}:")
print("\n".join(row[0] for row in cur.fetchall()))
# Keep the measurement repeatable without accumulating fixtures.
conn.rollback()
if __name__ == "__main__":
main()
+118
View File
@@ -0,0 +1,118 @@
"""Isolated before/after session-cache experiment; never used by the API.
Run against a local test database and Valkey. Creates and removes its own users.
The baseline reproduces the former two-read algorithm accepting cached identity.
"""
import json
import statistics
import sys
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app import Store
def main():
store = Store()
store.pool.open(wait=True)
store.init()
cache = store.cache_client()
users, tokens = [], []
try:
for _ in range(2):
users.append(store.insert_user("research_" + uuid.uuid4().hex[:16], "Research", "research-password"))
result = store.create_session(users[0]["id"], users[0]["username"])
token = result["token"]
tokens.append(token)
with store.connect() as conn:
canonical = store.fetch_session_by_token(token, conn)
forged = dict(canonical, user_id=users[1]["id"], user=users[1])
def baseline():
# Former algorithm: DB validity does not authenticate cached fields.
with store.connect() as conn:
db_session = store.fetch_session_by_token(token, conn)
if not store.is_session_valid(db_session):
return None
payload = cache.get(f"session:{token}")
if payload:
cached = json.loads(payload)
if store.is_session_valid(cached):
again = store.fetch_session_by_token(token, conn)
if store.is_session_valid(again):
return cached
store.cache_session(db_session)
return db_session
outputs = {}
for name, read in (("before", baseline), ("after", lambda: store.get_session_by_token(token))):
store.cache_session(canonical)
count = 0
original = store.fetch_session_by_token
def counted(*args, **kwargs):
nonlocal count
count += 1
return original(*args, **kwargs)
latencies = []
with patch.object(store, "fetch_session_by_token", side_effect=counted):
for _ in range(100):
start = time.perf_counter()
assert read()["user_id"] == users[0]["id"]
latencies.append((time.perf_counter() - start) * 1000)
# Force a cache writer between the DB read and cache read.
db_read, writer_done = threading.Event(), threading.Event()
first = True
def interleaved(*args, **kwargs):
nonlocal first
session = original(*args, **kwargs)
if first:
first = False
db_read.set()
if not writer_done.wait(5):
raise AssertionError("cache writer timed out")
return session
def writer():
if not db_read.wait(5):
raise AssertionError("DB reader timed out")
try:
cache.setex(f"session:{token}", 60, json.dumps(forged))
finally:
writer_done.set()
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(writer)
with patch.object(store, "fetch_session_by_token", side_effect=interleaved):
observed = read()
future.result()
outputs[name] = {
"requests": 100, "session_selects": count,
"mean_ms": round(statistics.mean(latencies), 3),
"p95_ms": round(sorted(latencies)[94], 3),
"concurrent_wrong_identity": observed["user_id"] != users[0]["id"],
}
# A cache restart/flush is a miss; delete only our key on shared fixtures.
cache.delete(f"session:{token}")
assert store.get_session_by_token(token)["user_id"] == users[0]["id"]
assert cache.exists(f"session:{token}")
assert outputs["before"]["concurrent_wrong_identity"]
assert not outputs["after"]["concurrent_wrong_identity"]
assert outputs["after"]["session_selects"] == 100
print(json.dumps({"results": outputs, "cache_miss_recovered": True,
"limitations": "Local sequential Store benchmark, warm DB; deterministic interleaving; baseline is former algorithm, not a deployed insecure API. No host-failure or HTTP throughput claim."}, indent=2))
finally:
for token in tokens:
store.delete_cached_session(token)
with store.connect() as conn:
for user in users:
conn.execute("DELETE FROM users WHERE id = %s", (user["id"],))
store.pool.close()
if __name__ == "__main__":
main()