[STAGE2] Event envelope + outbox/inbox idempotency (100→1)
lint / hygiene (pull_request) Failing after 41s
lint / hygiene (push) Failing after 39s
standard / check (pull_request) Successful in 13s
standard / check (push) Successful in 15s

This commit is contained in:
architect committed 2026-11-27 10:45:37 +03:00
1 parent c1f9136bbe
commit 8f8ee4186e
6 files changed
+259

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://buryans.ru/contracts/events/envelope-v1.json",
"title": "Buryans CloudEvent envelope v1",
"type": "object",
"additionalProperties": false,
"required": ["specversion", "id", "source", "type", "time", "idempotency_key", "data"],
"properties": {
"specversion": {"const": "1.0"},
"id": {"type": "string", "minLength": 1, "maxLength": 128},
"source": {"type": "string", "minLength": 1, "maxLength": 256},
"type": {"type": "string", "minLength": 1, "maxLength": 128},
"subject": {"type": "string", "maxLength": 256},
"time": {"type": "string", "format": "date-time"},
"datacontenttype": {"const": "application/json"},
"idempotency_key": {"type": "string", "minLength": 1, "maxLength": 256},
"correlation_id": {"type": "string", "maxLength": 128},
"causation_id": {"type": "string", "maxLength": 128},
"data": {"type": "object"}
}
}
+10
View File
@@ -35,6 +35,13 @@
| S1-08 | S1 | ACL/revocation tests | done | | security | 3 -> 0 -> 3 views; login true | 5 | G1 |
| S1-09 | S1 | Secret scan/redaction | done | | security | secret_scan 0; redaction residual 0 | 5 | G1 |
| S1-10 | S1 | Gate G1 review | done | | roman | owner acceptance; 10/10 media · Утром прокликать Gate G1 | 3 | G1 |
| S2-01 | S2 | CloudEvents envelope v1 | done | | architect | contracts/events/envelope-v1.json | 0 | |
| S2-02 | S2 | Outbox schema + enqueue | done | | architect | ops/events/schema.sql; enqueue | 0 | |
| S2-03 | S2 | Inbox + effects idempotency | done | | architect | repeat_test 100→1 | 0 | |
| S2-04 | S2 | NATS JetStream relay | open | | architect | pending | 0 | |
| S2-05 | S2 | Adapters + ownership matrix | open | | architect | pending | 0 | |
| S2-06 | S2 | pgvector pilot | open | | architect | pending | 0 | |
| S2-07 | S2 | Gate G2 proof | open | YES | architect | pending | 0 | G2 |
| U-01 | U | Approve PR #192 | done | | roman | chat approval 2026-11-26 · Открыть PR #192 и подтвердить архитектуру | 2 | none |
| U-02 | U | Seerr vs Jellyseerr decision | dropped | YES | roman | Seerr audit · Выбрать после evidence | 2 | none |
| U-03 | U | RAM/GPU/disk data | dropped | YES | roman | resource baseline · Прислать/подтвердить параметры | 2 | none |
@@ -47,11 +54,14 @@
- M / done: 7
- S0 / done: 10
- S1 / done: 10
- S2 / done: 3
- S2 / open: 4
- U / done: 2
- U / dropped: 3
## Пользовательская очередь
- **S2-07** — Gate G2 proof:
- **U-02** — Seerr vs Jellyseerr decision: Выбрать после evidence
- **U-03** — RAM/GPU/disk data: Прислать/подтвердить параметры
- **U-04** — Approve Stage1 write actions: Разрешить только после Gate G1
+44
View File
@@ -0,0 +1,44 @@
# Stage 2 — Event & Data
Статус: начат 2026-11-27.
Gate G2: повтор события 100 раз = один эффект; потеря webhook восстанавливается.
## Инкремент 1 — deterministic core (сделано)
- `contracts/events/envelope-v1.json` — CloudEvents envelope.
- `ops/events/schema.sql` — `events.outbox`, `events.inbox`, `events.effects`.
- `ops/events/event_store.py` — enqueue, consume, repeat_test.
- `repeat_test`: 100 повторов одного события → `first_effects=1`, `effects=1`.
## Задачи
| Код | Задача | Статус |
|---|---|---|
| S2-01 | CloudEvents envelope v1 | done |
| S2-02 | Outbox schema + enqueue | done |
| S2-03 | Inbox + effects idempotency | done |
| S2-04 | NATS JetStream relay | open |
| S2-05 | Adapters + ownership matrix | open |
| S2-06 | pgvector pilot | open |
| S2-07 | Gate G2 proof | open |
## Проверка
```bash
cd /root/buryan-infra
python3 ops/events/event_store.py
```
Ожидаемо:
```json
{"workers": 100, "first_effects": 1, "effects": 1}
```
## Следующий инкремент
NATS JetStream:
- outbox relay;
- stream + durable consumer;
- ack/redelivery;
- тест потери webhook.
+123
View File
@@ -0,0 +1,123 @@
"""Stage 2 event fabric: CloudEvents outbox + idempotent inbox/effects.
This is the deterministic PostgreSQL core used before the NATS relay.
It intentionally does not import NATS; the relay is a separate adapter.
"""
import json
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path
import psycopg2
from psycopg2.extras import Json
REQUIRED = ("specversion", "id", "source", "type", "time", "idempotency_key", "data")
def connect():
pw = os.getenv("PGPASSWORD")
if not pw:
pw = Path("/root/.pg-superuser-pass").read_text().strip()
return psycopg2.connect(
host=os.getenv("PGHOST", "192.168.1.151"),
dbname=os.getenv("PGDATABASE", "rag"),
user=os.getenv("PGUSER", "postgres"),
password=pw,
connect_timeout=5,
)
def init(conn):
sql = Path(__file__).with_name("schema.sql").read_text()
with conn.cursor() as cur:
cur.execute(sql)
conn.commit()
def event(event_id=None, source="buryans.test", type_="test.created",
idempotency_key=None, data=None, subject=None, correlation_id=None):
return {
"specversion": "1.0",
"id": event_id or str(uuid.uuid4()),
"source": source,
"type": type_,
"subject": subject,
"time": datetime.now(timezone.utc).isoformat(),
"datacontenttype": "application/json",
"idempotency_key": idempotency_key or str(uuid.uuid4()),
"correlation_id": correlation_id or str(uuid.uuid4()),
"data": data or {},
}
def validate(ev):
missing = [k for k in REQUIRED if not ev.get(k)]
if missing:
raise ValueError("missing fields: " + ",".join(missing))
if ev["specversion"] != "1.0":
raise ValueError("specversion must be 1.0")
return ev
def enqueue(conn, ev):
validate(ev)
with conn.cursor() as cur:
cur.execute("""
insert into events.outbox
(event_id, source, type, subject, time, idempotency_key,
correlation_id, causation_id, payload)
values (%s,%s,%s,%s,%s,%s,%s,%s,%s)
on conflict (idempotency_key) do nothing
returning event_id
""", (ev["id"], ev["source"], ev["type"], ev.get("subject"),
ev["time"], ev["idempotency_key"], ev.get("correlation_id"),
ev.get("causation_id"), Json(ev)))
row = cur.fetchone()
conn.commit()
return row[0] if row else None
def consume(conn, ev, consumer, effect_type, result=None):
"""Transactionally process once. Returns True for first effect, False for duplicate."""
validate(ev)
with conn:
with conn.cursor() as cur:
cur.execute("""
insert into events.inbox (consumer,event_id,idempotency_key,payload)
values (%s,%s,%s,%s)
on conflict (consumer,event_id) do nothing
returning id
""", (consumer, ev["id"], ev["idempotency_key"], Json(ev)))
if cur.fetchone() is None:
return False
cur.execute("""
insert into events.effects (idempotency_key,consumer,effect_type,result)
values (%s,%s,%s,%s)
on conflict (idempotency_key) do nothing
""", (ev["idempotency_key"], consumer, effect_type, Json(result or {})))
return True
def repeat_test(n=100):
conn = connect()
init(conn)
ev = event(idempotency_key="repeat-test", data={"n": 0})
with conn.cursor() as cur:
cur.execute("delete from events.outbox where idempotency_key=%s", ("repeat-test",))
cur.execute("delete from events.inbox where event_id=%s", (ev["id"],))
cur.execute("delete from events.effects where idempotency_key=%s", ("repeat-test",))
conn.commit()
first = 0
for _ in range(n):
if consume(conn, ev, "repeat-test", "counted", {"ok": True}):
first += 1
with conn.cursor() as cur:
cur.execute("select count(*) from events.effects where idempotency_key=%s", ("repeat-test",))
effects = cur.fetchone()[0]
conn.close()
return {"workers": n, "first_effects": first, "effects": effects}
if __name__ == "__main__":
print(json.dumps(repeat_test(), ensure_ascii=False))
+49
View File
@@ -0,0 +1,49 @@
-- Stage 2 event fabric: outbox/inbox/effects
CREATE SCHEMA IF NOT EXISTS events;
CREATE TABLE IF NOT EXISTS events.outbox (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
event_id text NOT NULL UNIQUE,
specversion text NOT NULL DEFAULT '1.0',
source text NOT NULL,
type text NOT NULL,
subject text,
time timestamptz NOT NULL,
datacontenttype text NOT NULL DEFAULT 'application/json',
idempotency_key text NOT NULL UNIQUE,
correlation_id text,
causation_id text,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','published','failed')),
attempts integer NOT NULL DEFAULT 0,
last_error text,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX IF NOT EXISTS outbox_pending_idx
ON events.outbox (status, created_at);
CREATE TABLE IF NOT EXISTS events.inbox (
id bigserial PRIMARY KEY,
consumer text NOT NULL,
event_id text NOT NULL,
idempotency_key text NOT NULL,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'processed'
CHECK (status IN ('processed','failed')),
received_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (consumer, event_id)
);
CREATE INDEX IF NOT EXISTS inbox_key_idx
ON events.inbox (idempotency_key);
CREATE TABLE IF NOT EXISTS events.effects (
idempotency_key text PRIMARY KEY,
consumer text NOT NULL,
effect_type text NOT NULL,
result jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
+12
View File
@@ -0,0 +1,12 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from event_store import repeat_test
def test_repeat_100_one_effect():
r = repeat_test(100)
assert r["workers"] == 100
assert r["first_effects"] == 1
assert r["effects"] == 1