add lab6
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
rule_files:
|
||||
- /workspace/infra/prometheus/alerts.yaml
|
||||
evaluation_interval: 5s
|
||||
tests:
|
||||
- interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{method="POST",route="/api/v1/chats/{chat_id}/messages",status_class="5xx"}'
|
||||
values: '0+50x30'
|
||||
- series: 'messenger_http_requests_total{method="POST",route="/api/v1/chats/{chat_id}/messages",status_class="2xx"}'
|
||||
values: '0+450x30'
|
||||
- series: 'messenger_queue_age_seconds{service_name="messenger-outbox"}'
|
||||
values: '60x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: 'API 5xx ratio exceeds 5%'
|
||||
runbook: 'Inspect API latency, traces and dependency spans; check DB readiness.'
|
||||
- eval_time: 2m
|
||||
alertname: MessengerQueueLag
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: 'Oldest queued job exceeds 30 seconds'
|
||||
runbook: 'Check worker health, busy/capacity, broker and consumer traces.'
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit local Docker tests: private bucket, uploader failover, S3 outage."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return subprocess.check_output(['docker', 'compose', *args], cwd=ROOT, input=input,
|
||||
text=True, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'stack did not recover')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--mode', required=True, choices=['private', 'failover', 's3-outage'])
|
||||
args = arguments(__doc__, configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
att = uploaded['json']
|
||||
content_path = '/api/v1/attachments/' + att['id'] + '/content'
|
||||
if args.mode == 'private':
|
||||
script = '''import sys, urllib.request, urllib.error
|
||||
url = "http://s3:8333/messenger-attachments/originals/" + sys.stdin.read().strip()
|
||||
try:
|
||||
urllib.request.urlopen(url, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403, error.code
|
||||
print("PASS: anonymous S3 GET returns 403 for an existing object")
|
||||
else:
|
||||
raise AssertionError("private object leaked")
|
||||
'''
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script, input=att['id']).strip())
|
||||
elif args.mode == 'failover':
|
||||
target = uploaded['headers']['X-Instance-Id']
|
||||
service = None
|
||||
for candidate in ('api-a', 'api-b'):
|
||||
container = compose('ps', '-q', candidate).strip()
|
||||
hostname = subprocess.check_output(['docker', 'inspect', '--format', '{{.Config.Hostname}}', container], text=True).strip()
|
||||
if hostname == target:
|
||||
service = candidate
|
||||
check(service is not None, 'uploading replica not found')
|
||||
try:
|
||||
compose('stop', service)
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
download = c.call('GET', content_path, actor=bob)
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'download did not recover')
|
||||
time.sleep(0.5)
|
||||
check(download['headers']['X-Instance-Id'] != target, 'download used stopped uploader')
|
||||
check(download['bytes'] == data, 'original changed after stopping uploader')
|
||||
print('PASS: uploaded via ' + service + '; stopped that container; original downloaded through another replica')
|
||||
finally:
|
||||
compose('start', service)
|
||||
wait_ready(c)
|
||||
else:
|
||||
try:
|
||||
compose('stop', 's3')
|
||||
# Direct API request inside the network: LB excludes unready backends.
|
||||
script = '''import json, sys, urllib.request, urllib.error
|
||||
payload = json.load(sys.stdin)
|
||||
for method, path, body, headers in [
|
||||
("GET", "/health/ready", None, {}),
|
||||
("GET", payload["path"], None, {"Authorization": "Bearer " + payload["token"]}),
|
||||
("POST", payload["upload_path"], bytes.fromhex(payload["bytes"]),
|
||||
{"Authorization": "Bearer " + payload["token"], "Content-Type": "image/png"}),
|
||||
]:
|
||||
req = urllib.request.Request("http://localhost:8080" + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503, error.code
|
||||
document = json.load(error)
|
||||
assert document["error"]["code"] == "unavailable"
|
||||
assert document["error"]["request_id"] == error.headers["X-Request-Id"]
|
||||
else:
|
||||
raise AssertionError("S3 outage was not reported")
|
||||
assert urllib.request.urlopen("http://localhost:8080/health/live").status == 200
|
||||
print("PASS: S3 outage gives 503 for readiness, download and upload; liveness stays 200")
|
||||
'''
|
||||
payload = {'path': content_path, 'token': bob['token'], 'bytes': data.hex(),
|
||||
'upload_path': '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'}
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script,
|
||||
input=json.dumps(payload)).strip())
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
# HeadBucket/read recovery alone does not prove the write path is ready.
|
||||
# Use the same write-probing bootstrap as the documented restart hook.
|
||||
compose('run', '--rm', '--no-deps', 's3-init')
|
||||
wait_ready(c)
|
||||
check(c.call('GET', content_path, actor=bob)['bytes'] == data, 'original lost after S3 outage')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after-recovery.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
print('PASS: original available and new upload accepted after S3 restart/bootstrap')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attachment contract checks against the running lab5 stack."""
|
||||
import hashlib
|
||||
import http.client
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(data, mime='image/png', filename='photo.png', status=202, actor=alice):
|
||||
return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data,
|
||||
headers={'Content-Type': mime}, schema='Attachment' if status == 202 else None)
|
||||
|
||||
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (32, 20), 'blue').save(buf, fmt)
|
||||
data = buf.getvalue()
|
||||
att = upload(data, mime)['json']
|
||||
check(att['variants'] == [] and att['status'] == 'queued', 'wrong attachment state')
|
||||
att = c.wait_ready(bob, att)
|
||||
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum')
|
||||
content_path = '/api/v1/attachments/' + att['id']
|
||||
check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att,
|
||||
'metadata changed')
|
||||
check(c.call('GET', content_path + '/content', actor=bob)['bytes'] == data, 'bytes changed')
|
||||
c.call('GET', content_path, 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 401)
|
||||
c.call('GET', content_path + '/content?variant=thumbnail', actor=bob)
|
||||
message = c.message(bob, chat, '', attachments=[att['id']])['json']
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
|
||||
actor=alice, schema='MessagePage')['json']['items']
|
||||
check(message in history, 'attachment message missing in history')
|
||||
print('PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL')
|
||||
|
||||
for name in ('../x.png', 'x/y.png', 'x\\y.png', 'x\x00.png', 'x\n.png', 'x\x7f.png', ' ', 'x' * 256):
|
||||
upload(png, filename=name, status=400)
|
||||
upload(png, mime='image/jpeg', status=415)
|
||||
upload(b'not an image', status=415)
|
||||
upload(png[:30], status=415)
|
||||
upload(png, mime='application/octet-stream', status=415)
|
||||
upload(png, status=404, actor=eve)
|
||||
upload(b'x' * (10485760 + 1), status=413)
|
||||
|
||||
# Valid PNG header with an oversized canvas: reject before attempting pixel decoding.
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 8001, 5000, 8, 2, 0, 0, 0))
|
||||
huge += chunk(b'IDAT', zlib.compress(b'')) + chunk(b'IEND', b'')
|
||||
upload(huge, status=413)
|
||||
|
||||
# No Content-Length: limits must also work for chunked requests.
|
||||
url = urlsplit(c.base)
|
||||
connection = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
|
||||
connection.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161),
|
||||
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'},
|
||||
encode_chunked=True)
|
||||
response = connection.getresponse()
|
||||
check(response.status == 413, 'chunked upload bypassed byte limit')
|
||||
response.read()
|
||||
connection.close()
|
||||
print('PASS: filename, MIME, malformed image, byte/pixel and chunked limits')
|
||||
|
||||
att = upload(png)['json']
|
||||
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
for target, ids, code in ((chat, [str(uuid.uuid4())], 404),
|
||||
(other_chat, [att['id']], 404),
|
||||
(chat, [att['id'], att['id']], 400)):
|
||||
c.call('POST', '/api/v1/chats/' + target['id'] + '/messages', code, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, 'same', key=key)['json']
|
||||
check(c.message(alice, chat, 'same', key=key, attachments=[])['json'] == first,
|
||||
'omitted and empty attachment_ids differ')
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, '', key=key, attachments=[att['id']])['json']
|
||||
check(c.message(alice, chat, '', key=key, attachments=[att['id']])['json'] == first, 'replay differs')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key})
|
||||
print('PASS: attachment scope, duplicates and idempotency normalization')
|
||||
|
||||
# Exact limits are accepted; original bytes (including PNG trailing data) survive.
|
||||
exact = png + b'\0' * (10485760 - len(png))
|
||||
att = upload(exact)['json']
|
||||
c.wait_ready(bob, att)
|
||||
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact,
|
||||
'10 MiB original changed')
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (8000, 5000)).save(buf, 'PNG')
|
||||
att = upload(buf.getvalue())['json']
|
||||
check(att['size_bytes'] == len(buf.getvalue()), '40M pixel upload failed')
|
||||
print('PASS: inclusive 10 MiB and 40 million pixel boundaries')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,83 @@
|
||||
rule_files:
|
||||
- /workspace/infra/prometheus/alerts.yaml
|
||||
evaluation_interval: 5s
|
||||
tests:
|
||||
- name: healthy
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+0x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+0x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnSlow, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnSlow, exp_alerts: []}
|
||||
- name: brief severe spike and recovery
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+100x12 1200+0x8 1200+100x60'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+0x12 0+100x8 800+0x60'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m30s
|
||||
alertname: MessengerApiBurnFast
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: critical, slo: api, burn: fast}
|
||||
exp_annotations: {summary: 'api SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- {eval_time: 3m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- name: sustained moderate degradation
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+80x80'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+20x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+20x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- eval_time: 5m
|
||||
alertname: MessengerApiBurnSlow
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, slo: api, burn: slow}
|
||||
exp_annotations: {summary: 'api SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- eval_time: 5m
|
||||
alertname: MessengerReadyBurnSlow
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, slo: ready, burn: slow}
|
||||
exp_annotations: {summary: 'ready SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- name: low-volume guard
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+1x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+1x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+1x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- name: late ready events fast burn
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x30'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerReadyBurnFast
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: critical, slo: ready, burn: fast}
|
||||
exp_annotations: {summary: 'ready SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Export synthetic trace/log evidence through Grafana; credentials never enter artifacts."""
|
||||
import argparse
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
auth = 'Basic ' + base64.b64encode(('admin:' + (ROOT/'secrets/grafana_password').read_text().strip()).encode()).decode()
|
||||
def get(source, path, params=None):
|
||||
url = f'http://127.0.0.1:3000/api/datasources/proxy/uid/{source}/' + path
|
||||
if params: url += '?' + urllib.parse.urlencode(params)
|
||||
with urllib.request.urlopen(urllib.request.Request(url,headers={'Authorization':auth}),timeout=15) as r:
|
||||
return json.load(r)
|
||||
|
||||
def capture(trace_id=None, query=None):
|
||||
query = query or '{service_name="messenger-api"} | status="503"'
|
||||
if trace_id:
|
||||
query = '{service_name=~"messenger-api|messenger-worker"} | trace_id="' + trace_id + '"'
|
||||
logs = get('loki','loki/api/v1/query_range',{'query':query,'since':'30m','limit':20,'direction':'backward'})
|
||||
if not trace_id:
|
||||
for stream in logs['data']['result']:
|
||||
for value in stream['values']:
|
||||
metadata = dict(stream['stream'])
|
||||
if len(value)>2: metadata.update(value[2])
|
||||
trace_id = metadata.get('trace_id')
|
||||
if trace_id: break
|
||||
if trace_id: break
|
||||
if not trace_id:
|
||||
raise RuntimeError('No correlated log/trace found')
|
||||
trace = get('tempo','api/traces/'+trace_id)
|
||||
return {'captured_at':datetime.now(timezone.utc).isoformat(),'query':query,'trace_id':trace_id,'logs':logs,'trace':trace}
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser();parser.add_argument('--trace-id');parser.add_argument('--output',required=True)
|
||||
args=parser.parse_args()
|
||||
result=capture(args.trace_id)
|
||||
(ROOT/args.output).write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
|
||||
print('Saved correlated evidence:',args.output,'trace_id:',result['trace_id'])
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Execute every provisioned PromQL target against the running Grafana datasource."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('capture',ROOT/'student-tests/capture_observability.py')
|
||||
capture=importlib.util.module_from_spec(spec);spec.loader.exec_module(capture)
|
||||
dashboard=json.loads((ROOT/'infra/grafana/dashboards/messenger.json').read_text())
|
||||
results=[]
|
||||
for panel in dashboard['panels']:
|
||||
for target in panel.get('targets',[]):
|
||||
if 'expr' not in target:continue
|
||||
query=target['expr'].replace('$__rate_interval','1m').replace('$__interval','5s')
|
||||
result=capture.get('prometheus','api/v1/query',{'query':query})
|
||||
assert result['status']=='success',result
|
||||
results.append({'panel':panel['title'],'query':query,'series':len(result['data']['result'])})
|
||||
(ROOT/'evidence/review-dashboard.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS:',len(results),'dashboard queries; empty targets:',sum(r['series']==0 for r in results))
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Verify exported parent relationships and the completed retry, not just trace existence."""
|
||||
import base64
|
||||
import json
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
data=json.loads((ROOT/'evidence/review-retry-trace.json').read_text())
|
||||
spans=[s for batch in data['trace']['batches'] for scope in batch.get('scopeSpans',[]) for s in scope.get('spans',[])]
|
||||
by_id={s['spanId']:s for s in spans}
|
||||
counts=Counter(s['name'] for s in spans)
|
||||
producers=[s for s in spans if s['kind']=='SPAN_KIND_PRODUCER']
|
||||
consumers=[s for s in spans if s['kind']=='SPAN_KIND_CONSUMER']
|
||||
assert len(producers)>=2 and consumers,counts
|
||||
for producer in producers:
|
||||
ancestor = producer
|
||||
for _ in range(len(spans)):
|
||||
ancestor = by_id[ancestor['parentSpanId']]
|
||||
if ancestor['kind']=='SPAN_KIND_SERVER': break
|
||||
else: raise AssertionError('producer has no API ancestor')
|
||||
for consumer in consumers:
|
||||
assert by_id[consumer['parentSpanId']]['kind']=='SPAN_KIND_PRODUCER'
|
||||
assert counts['postgres.complete_attachment_job']>=1,counts
|
||||
assert any(s['name'].startswith('s3.') for s in spans),counts
|
||||
assert all(base64.b64decode(s['traceId']).hex()==data['trace_id'] for s in spans)
|
||||
services={stream['stream']['service_name'] for stream in data['logs']['data']['result']}
|
||||
assert {'messenger-api','messenger-worker'}<=services,services
|
||||
result={'trace_id':data['trace_id'],'span_count':len(spans),'span_names':dict(counts),
|
||||
'producer_count':len(producers),'consumer_count':len(consumers),'log_services':sorted(services),
|
||||
'parent_relationships':'PASS','note':'Abrupt os._exit may lose unfinished spans of the crashed attempt; redelivery and committed retry remain visible.'}
|
||||
(ROOT/'evidence/review-retry-summary.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('PASS:',json.dumps(result))
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Один ключ одновременно через LB создаёт ровно одно сообщение."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client()
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = "concurrent idempotency " + key
|
||||
|
||||
def send(_number: int):
|
||||
return Client().message(alice, chat, text, key=key)["json"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
replies = list(pool.map(send, range(16)))
|
||||
check(all(reply == replies[0] for reply in replies), "replays returned different messages")
|
||||
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
history = client.call("GET", path, actor=alice, schema="MessagePage")["json"]["items"]
|
||||
check(sum(message["id"] == replies[0]["id"] for message in history) == 1, "concurrent retries created duplicates")
|
||||
print("PASS: concurrent idempotency through load balancer")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check real producer payloads and redeliver a complete persisted message."""
|
||||
import json
|
||||
import time
|
||||
from jsonschema import Draft202012Validator, FormatChecker
|
||||
from pipeline_integration import ROOT, Client, remote, duplicate, snapshot, wait, check
|
||||
|
||||
|
||||
def main():
|
||||
c = Client('http://localhost:8080', timeout=30)
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
att, _ = c.attachment(actor, chat)
|
||||
wait(c, actor, att)
|
||||
payloads = remote('''rows = await db.pool.fetch('SELECT payload FROM attachment_outbox')
|
||||
print(json.dumps([json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload'] for row in rows]))''')
|
||||
validator = Draft202012Validator(json.loads((ROOT / 'contracts/jobs.schema.json').read_text()), format_checker=FormatChecker())
|
||||
for payload in payloads:
|
||||
validator.validate(payload)
|
||||
before = snapshot(att)
|
||||
duplicate(att)
|
||||
duplicate(att)
|
||||
time.sleep(3)
|
||||
check(snapshot(att) == before, 'persisted redelivery changed result')
|
||||
result = dict(status='PASS', validated_outbox_payloads=len(payloads),
|
||||
extra_payload_fields=False, persisted_redelivery_noop=True)
|
||||
(ROOT / 'evidence/job-contract.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Offline regression checks for delivery and terminal-state safety."""
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.worker import process_locked as process, settle_delivery
|
||||
from concurrent.futures import Future
|
||||
from src.broker import _publish_to
|
||||
|
||||
|
||||
class CriticalTests(unittest.IsolatedAsyncioTestCase):
|
||||
def test_failed_or_unrecorded_work_is_requeued(self):
|
||||
for result in (False, None, RuntimeError('database unavailable')):
|
||||
future, channel = Future(), MagicMock()
|
||||
if isinstance(result, Exception):
|
||||
future.set_exception(result)
|
||||
else:
|
||||
future.set_result(result)
|
||||
settle_delivery(channel, 7, future)
|
||||
channel.basic_ack.assert_not_called()
|
||||
channel.basic_nack.assert_called_once_with(7, requeue=True)
|
||||
|
||||
def test_durable_success_is_acked(self):
|
||||
future, channel = Future(), MagicMock()
|
||||
future.set_result(True)
|
||||
settle_delivery(channel, 7, future)
|
||||
channel.basic_ack.assert_called_once_with(7)
|
||||
channel.basic_nack.assert_not_called()
|
||||
|
||||
async def test_outbox_decodes_jsonb(self):
|
||||
store = PostgresStore('unused')
|
||||
store._pool = AsyncMock()
|
||||
payload = {'type': 'attachment.process.v1', 'attachment_id': str(uuid4())}
|
||||
store.pool.fetch.return_value = [{'id': uuid4(), 'payload': json.dumps(payload)}]
|
||||
event, = await store.due_outbox_events()
|
||||
self.assertEqual(json.loads(json.dumps(event['payload'])), payload)
|
||||
|
||||
async def run_processing(self, committed):
|
||||
store, s3 = AsyncMock(), AsyncMock()
|
||||
stamp = datetime.now(timezone.utc)
|
||||
store.claim_attachment_job.return_value = {
|
||||
'claim_time': stamp, 'staging_key': 'staging/test',
|
||||
'content_type': 'image/png', 'size_bytes': 1, 'sha256': 'unused',
|
||||
}
|
||||
store.complete_attachment_job.return_value = committed
|
||||
store.ready_seconds.return_value = 0.25
|
||||
s3.settings = SimpleNamespace(max_pixels=40000000)
|
||||
s3.download_key.return_value = b'fixture'
|
||||
s3.delete.side_effect = RuntimeError('storage temporarily unavailable')
|
||||
payload = {'attachment_id': str(uuid4())}
|
||||
with patch('src.worker.render_isolated', return_value=[('thumbnail', b'jpeg', 'image/jpeg', 1, 1)]):
|
||||
outcome = await process(store, s3, payload, 60)
|
||||
self.assertEqual(outcome, "success" if committed else "skipped")
|
||||
self.assertEqual(store.complete_attachment_job.call_args.args[-1], stamp)
|
||||
return store, s3
|
||||
|
||||
async def test_cleanup_error_does_not_retry_ready(self):
|
||||
store, s3 = await self.run_processing(True)
|
||||
s3.delete.assert_awaited_once()
|
||||
store.retry_attachment_job.assert_not_awaited()
|
||||
|
||||
async def test_stale_completion_keeps_staging(self):
|
||||
_, s3 = await self.run_processing(False)
|
||||
s3.delete.assert_not_awaited()
|
||||
|
||||
async def test_duplicate_is_skipped_not_successful(self):
|
||||
store, s3 = AsyncMock(), AsyncMock()
|
||||
store.claim_attachment_job.return_value = None
|
||||
result = await process(store, s3, {'attachment_id': str(uuid4())}, 60)
|
||||
self.assertEqual(result, 'skipped')
|
||||
store.complete_attachment_job.assert_not_awaited()
|
||||
s3.copy.assert_not_awaited()
|
||||
|
||||
async def test_stale_claim_cannot_publish_metadata(self):
|
||||
store = PostgresStore('unused')
|
||||
connection = AsyncMock()
|
||||
connection.fetchval.return_value = None
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
self.assertFalse(await store.complete_attachment_job(uuid4(), 'original', [], datetime.now(timezone.utc)))
|
||||
connection.execute.assert_not_awaited()
|
||||
|
||||
async def test_retry_of_terminal_or_stale_attempt_is_noop(self):
|
||||
store = PostgresStore('unused')
|
||||
connection = AsyncMock()
|
||||
connection.fetchrow.return_value = None
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
self.assertFalse(await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc)))
|
||||
connection.execute.assert_not_awaited()
|
||||
|
||||
def test_dlq_waits_for_publisher_confirm(self):
|
||||
connection = MagicMock()
|
||||
with patch('src.broker._connection', return_value=connection):
|
||||
_publish_to('dlq', {'failure': 'invalid_job'})
|
||||
connection.channel.return_value.confirm_delivery.assert_called_once()
|
||||
self.assertTrue(connection.channel.return_value.basic_publish.call_args.kwargs['mandatory'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Destructive-to-availability tests on the local lab stack; volumes preserved.
|
||||
|
||||
Only synthetic attachments created here are mutated. Tokens stay in memory.
|
||||
Run sequentially, never alongside load or another fault test.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def compose(*args, env=None, source=None):
|
||||
result = subprocess.run(['docker', 'compose', *args], cwd=ROOT,
|
||||
env=dict(os.environ, **(env or {})), input=source,
|
||||
text=True, capture_output=True, timeout=150)
|
||||
check(result.returncode == 0, 'compose failed: ' + ' '.join(args[:4]) + '\n' + result.stderr[-1000:])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def remote(body, **values):
|
||||
source = '''import asyncio, json, os
|
||||
from uuid import UUID
|
||||
from src.config import load_settings
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.storage.s3 import S3Store, S3Settings
|
||||
from src.broker import publish
|
||||
V = json.loads(%r)
|
||||
async def main():
|
||||
db = PostgresStore(load_settings().database_url)
|
||||
await db.connect()
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
%s
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
asyncio.run(main())
|
||||
''' % (json.dumps(values), '\n'.join(' ' + line for line in body.splitlines()))
|
||||
return json.loads(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-', source=source))
|
||||
|
||||
|
||||
def record(name, **facts):
|
||||
RESULTS.append(dict(test=name, status='PASS', **facts))
|
||||
print('PASS: ' + name, flush=True)
|
||||
(ROOT / 'evidence/pipeline-integration.json').write_text(json.dumps(RESULTS, indent=2) + '\n')
|
||||
|
||||
|
||||
def ready(c):
|
||||
deadline = time.monotonic() + 90
|
||||
successes = 0
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call('GET', '/health/ready')
|
||||
successes += 1
|
||||
if successes >= 5:
|
||||
return
|
||||
time.sleep(.5)
|
||||
except Failure:
|
||||
successes = 0
|
||||
time.sleep(.5)
|
||||
raise Failure('API did not recover')
|
||||
|
||||
|
||||
def wait(c, actor, att, status='ready', timeout=120):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = c.call('GET', '/api/v1/attachments/' + att['id'], actor=actor, schema='Attachment')['json']
|
||||
except Failure:
|
||||
time.sleep(.25)
|
||||
continue
|
||||
if value['status'] == status:
|
||||
return value
|
||||
check(value['status'] != 'failed' or status == 'failed', 'unexpected failed attachment')
|
||||
time.sleep(.25)
|
||||
raise Failure('attachment did not reach ' + status)
|
||||
|
||||
|
||||
def snapshot(att):
|
||||
return remote('''row = await db.pool.fetchrow("SELECT a.status, j.attempt, j.job_id, a.original_key, a.staging_key FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.id=$1", UUID(V['id']))
|
||||
objects = sorted(list(await s3.list('originals/' + V['id'] + '/')) + list(await s3.list('variants/' + V['id'] + '/')))
|
||||
print(json.dumps(dict(row) | {'objects': objects}, default=str))''', id=att['id'])
|
||||
|
||||
|
||||
def duplicate(att):
|
||||
return remote('''payload = await db.pool.fetchval("SELECT o.payload FROM attachment_outbox o JOIN attachment_jobs j ON j.job_id=o.job_id WHERE j.attachment_id=$1 ORDER BY o.created_at LIMIT 1", UUID(V['id']))
|
||||
await publish(json.loads(payload) if isinstance(payload, str) else payload)
|
||||
print('true')''', id=att['id'])
|
||||
|
||||
|
||||
def main():
|
||||
c = Client('http://localhost:8080', timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
|
||||
# No worker: HTTP admission and message creation must remain asynchronous.
|
||||
compose('stop', '-t', '2', 'worker')
|
||||
att, data = c.attachment(alice, chat)
|
||||
check(att['status'] == 'queued', 'upload is not queued with stopped worker')
|
||||
c.message(alice, chat, 'queued attachment', attachments=[att['id']])
|
||||
time.sleep(2)
|
||||
compose('restart', 'broker')
|
||||
compose('up', '-d', '--no-deps', '--wait', 'broker')
|
||||
compose('restart', 'api-a', 'api-b')
|
||||
ready(c)
|
||||
compose('start', 'worker')
|
||||
completed = wait(c, bob, att)
|
||||
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == data, 'original changed')
|
||||
check({v['name'] for v in completed['variants']} == {'thumbnail', 'crop', 'optimized'}, 'variants missing')
|
||||
record('stopped worker, queued message, broker/API restart, ready', attachment_id=att['id'])
|
||||
|
||||
before = snapshot(att)
|
||||
duplicate(att)
|
||||
duplicate(att)
|
||||
time.sleep(3)
|
||||
check(snapshot(att) == before, 'duplicate changed result or created S3 objects')
|
||||
refused = remote("print(json.dumps(await db.replay_failed_attachment(UUID(V['id']))))", id=att['id'])
|
||||
check(refused is False, 'ready replay accepted')
|
||||
record('duplicate delivery and replay of ready are no-ops', object_count=len(before['objects']))
|
||||
|
||||
# Pause publication so the API crash is demonstrably before any publish.
|
||||
compose('stop', '-t', '2', 'outbox')
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b', env={'OUTBOX_FAULT_AFTER_COMMIT': '1'})
|
||||
ready(c)
|
||||
fault_actor, _, _, fault_chat = c.bootstrap()
|
||||
try:
|
||||
c.attachment(fault_actor, fault_chat)
|
||||
raise AssertionError('crash hook did not interrupt upload')
|
||||
except Failure:
|
||||
pass
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b')
|
||||
ready(c)
|
||||
row = remote('''rows = await db.pool.fetch("SELECT a.id, o.published_at FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id JOIN attachment_outbox o ON o.job_id=j.job_id WHERE a.chat_id=$1", UUID(V['chat']))
|
||||
assert len(rows) == 1 and rows[0]['published_at'] is None
|
||||
print(json.dumps({'id': str(rows[0]['id'])}))''', chat=fault_chat['id'])
|
||||
compose('start', 'outbox')
|
||||
wait(c, fault_actor, row)
|
||||
record('crash after COMMIT before publish recovered from existing outbox', attachment_id=row['id'])
|
||||
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', env={'WORKER_FAULT_AFTER_S3_PUT': '1', 'JOB_TIMEOUT_SECONDS': '10'})
|
||||
att, _ = c.attachment(alice, chat)
|
||||
wait(c, alice, att)
|
||||
snap = snapshot(att)
|
||||
check(snap['attempt'] >= 2 and len(snap['objects']) >= 8, 'side effect crash/lease retry not observed')
|
||||
marker = compose('exec', '-T', 'worker', 'cat', '/tmp/worker-fault-after-s3')
|
||||
check(marker == att['id'], 'wrong fault target')
|
||||
record('worker crash after S3 before commit/ack, lease recovery', attempt=snap['attempt'], objects_before_cleanup=len(snap['objects']))
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker')
|
||||
|
||||
# Select only this test's unreferenced attempt keys for cleanup.
|
||||
cleaned = remote('''from argparse import Namespace
|
||||
from src.reconcile import run
|
||||
keys = V['keys']
|
||||
result = await run(Namespace(apply=True, grace_seconds=0, object_key=keys))
|
||||
print(json.dumps(result['deleted']))''', keys=snap['objects'])
|
||||
check(len(cleaned) == 4, 'stale attempt objects not cleaned safely')
|
||||
check(len(snapshot(att)['objects']) == 4, 'live attempt affected by cleanup')
|
||||
wait(c, alice, att)
|
||||
record('targeted orphan cleanup preserves committed attempt', deleted=len(cleaned))
|
||||
|
||||
# Lose only this synthetic staging object to exercise transient retry exhaustion.
|
||||
compose('stop', '-t', '2', 'worker')
|
||||
att, data = c.attachment(alice, chat)
|
||||
remote("await s3.delete('staging/' + V['id'] + '/original')\nprint('true')", id=att['id'])
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker', env={'JOB_MAX_ATTEMPTS': '2'})
|
||||
failed = wait(c, alice, att, 'failed')
|
||||
snap = snapshot(att)
|
||||
check(snap['attempt'] == 2 and failed['error_code'] == 'retry_exhausted', 'unbounded/wrong retry')
|
||||
# Restore exactly the bytes originally accepted, then explicit failed-only replay.
|
||||
import base64
|
||||
replayed = remote('''from io import BytesIO
|
||||
import base64
|
||||
content = base64.b64decode(V['data'])
|
||||
await s3.put('staging/' + V['id'] + '/original', BytesIO(content), len(content), 'image/png')
|
||||
print(json.dumps(await db.replay_failed_attachment(UUID(V['id']))))''', id=att['id'], data=base64.b64encode(data).decode())
|
||||
check(replayed, 'failed replay refused')
|
||||
wait(c, alice, att)
|
||||
record('bounded transient retry, failed registry and explicit replay', attempts_before_replay=snap['attempt'])
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker')
|
||||
|
||||
# Real Linux child with deliberately insufficient address space.
|
||||
memory = remote('''import subprocess
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
buf = BytesIO(); Image.new('RGB', (2400, 2400)).save(buf, 'PNG')
|
||||
env = dict(os.environ, RENDER_MEMORY_MB='120')
|
||||
p = subprocess.run(['/app/.venv/bin/python', '-m', 'src.render'], input=buf.getvalue(), capture_output=True, env=env, timeout=30)
|
||||
print(json.dumps({'returncode': p.returncode}))''')
|
||||
check(memory['returncode'] == 21, 'Linux memory limit did not produce bounded resource failure')
|
||||
record('Linux renderer memory limit', **memory)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', '--wait', 'api-a', 'api-b', 'worker', 'outbox')
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real PostgreSQL/S3/RabbitMQ invariant and security checks, synthetic data only."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
from pipeline_integration import Client, check, compose, remote, wait, ROOT
|
||||
|
||||
|
||||
def main():
|
||||
results = []
|
||||
c = Client('http://localhost:8080', timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
att, _ = c.attachment(alice, chat)
|
||||
wait(c, bob, att)
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
for name, fmt, bound in (('thumbnail', 'JPEG', 256), ('crop', 'JPEG', 128), ('optimized', 'WEBP', 1280)):
|
||||
content = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + name, actor=bob)['bytes']
|
||||
with Image.open(BytesIO(content)) as image:
|
||||
check(image.format == fmt and max(image.size) <= bound and not image.getexif(), 'variant format/size/EXIF')
|
||||
if name == 'crop':
|
||||
check(image.size == (128, 128), 'crop dimensions')
|
||||
results.append('actual thumbnail/crop/WebP formats, dimensions and removed EXIF')
|
||||
# Verify actual private object key, not a nonexistent legacy key.
|
||||
private = remote('''import urllib.request, urllib.error
|
||||
key = await db.pool.fetchval('SELECT original_key FROM attachments WHERE id=$1', UUID(V['id']))
|
||||
try:
|
||||
urllib.request.urlopen('http://s3:8333/' + s3.settings.bucket + '/' + key, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403, error.code
|
||||
else:
|
||||
raise AssertionError('anonymous object leaked')
|
||||
print('true')''', id=att['id'])
|
||||
check(private, 'private S3 check failed')
|
||||
for variant in ('thumbnail', 'crop', 'optimized'):
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=' + variant, 404, actor=eve)
|
||||
results.append('anonymous S3 403 on existing object; variant ACL 404')
|
||||
|
||||
lock = remote('''import time
|
||||
entered = asyncio.Event()
|
||||
async def writer():
|
||||
async with db.attachment_transaction():
|
||||
entered.set()
|
||||
await asyncio.sleep(1)
|
||||
task = asyncio.create_task(writer())
|
||||
await entered.wait()
|
||||
started = time.monotonic()
|
||||
async with db.attachment_transaction(maintenance=True):
|
||||
waited = time.monotonic() - started
|
||||
await task
|
||||
assert waited >= .9, waited
|
||||
print(json.dumps({'maintenance_wait_seconds': waited}))''')
|
||||
results.append(lock)
|
||||
|
||||
# Poison staging only for a newly created synthetic attachment and update its
|
||||
# digest so invalid-image classification (not transport checksum) is exercised.
|
||||
compose('stop', '-t', '2', 'worker')
|
||||
guarded, _ = c.attachment(alice, chat)
|
||||
fence = remote('''key = UUID(V['id'])
|
||||
job_id = await db.pool.fetchval('SELECT job_id FROM attachment_jobs WHERE attachment_id=$1', key)
|
||||
before = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id)
|
||||
await db.pool.execute("UPDATE attachment_jobs SET updated_at=now()-interval '61 seconds' WHERE attachment_id=$1", key)
|
||||
await db.schedule_due_jobs()
|
||||
after = await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id)
|
||||
assert after == before + 1, 'unclaimed published job stranded'
|
||||
assert await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', key) == 1
|
||||
await db.schedule_due_jobs()
|
||||
assert await db.pool.fetchval('SELECT count(*) FROM attachment_outbox WHERE job_id=$1', job_id) == after, 'watchdog floods outbox'
|
||||
first = await db.claim_attachment_job(key, 30)
|
||||
assert first is not None
|
||||
assert await db.retry_attachment_job(key, 5, 30, first['claim_time'])
|
||||
assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed retry delay'
|
||||
await db.pool.execute("UPDATE attachment_jobs SET next_attempt_at=now() WHERE attachment_id=$1", key)
|
||||
await db.schedule_due_jobs()
|
||||
second = await db.claim_attachment_job(key, 30)
|
||||
assert second is not None and second['attempt'] == 2
|
||||
assert not await db.complete_attachment_job(key, 'invalid-stale-key', [], first['claim_time'])
|
||||
assert not await db.retry_attachment_job(key, 5, 0, first['claim_time'])
|
||||
await db.pool.execute("UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE attachment_id=$1", key)
|
||||
assert await db.claim_attachment_job(key, 30) is None, 'duplicate bypassed lease attempt accounting'
|
||||
await db.schedule_due_jobs()
|
||||
third = await db.claim_attachment_job(key, 30)
|
||||
assert third['attempt'] == 3
|
||||
assert await db.retry_attachment_job(key, 5, 0, third['claim_time'])
|
||||
print('true')''', id=guarded['id'])
|
||||
check(fence, 'SQL fencing/backoff invariant')
|
||||
results.append('real SQL: queued watchdog republishes without attempt increment/flood; duplicate respects backoff; expired lease counted; stale completion/retry fenced')
|
||||
att, _ = c.attachment(alice, chat)
|
||||
remote('''from io import BytesIO
|
||||
from hashlib import sha256
|
||||
data = b'invalid image payload'
|
||||
await s3.put('staging/' + V['id'] + '/original', BytesIO(data), len(data), 'image/png')
|
||||
await db.pool.execute('UPDATE attachments SET size_bytes=$2, sha256=$3 WHERE id=$1', UUID(V['id']), len(data), sha256(data).hexdigest())
|
||||
print('true')''', id=att['id'])
|
||||
compose('start', 'worker')
|
||||
wait(c, alice, guarded)
|
||||
failed = wait(c, alice, att, 'failed')
|
||||
check(failed['error_code'] == 'invalid_image', 'permanent classification failed')
|
||||
attempt = remote("print(await db.pool.fetchval('SELECT attempt FROM attachment_jobs WHERE attachment_id=$1', UUID(V['id'])))", id=att['id'])
|
||||
check(attempt == 1, 'permanent error retried')
|
||||
results.append('permanent invalid_image reaches failed on attempt 1')
|
||||
|
||||
# DLQ uses confirmed persistent publication; count change avoids consuming
|
||||
# messages belonging to a different test.
|
||||
dlq = remote('''from src.broker import _connection, _publish, DLQ
|
||||
connection = _connection(); channel = connection.channel()
|
||||
before = channel.queue_declare(queue=DLQ, durable=True).method.message_count
|
||||
connection.close()
|
||||
_publish({'malformed': True})
|
||||
print(json.dumps({'before': before}))''')
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
count = remote('''from src.broker import _connection, DLQ
|
||||
connection = _connection()
|
||||
print(connection.channel().queue_declare(queue=DLQ, durable=True).method.message_count)
|
||||
connection.close()''')
|
||||
if count > dlq['before']:
|
||||
break
|
||||
time.sleep(.5)
|
||||
check(count == dlq['before'] + 1, 'invalid job not delivered to DLQ')
|
||||
results.append('malformed broker message delivered to DLQ')
|
||||
|
||||
# Actual Linux child timeout: no renderer can finish within this deadline.
|
||||
timeout = remote('''from src.worker import render_isolated
|
||||
try:
|
||||
render_isolated(b'x', .000001)
|
||||
except TimeoutError:
|
||||
print('true')
|
||||
else:
|
||||
raise AssertionError('timeout not enforced')''')
|
||||
check(timeout, 'timeout missing')
|
||||
results.append('Linux render subprocess killed/reaped on deadline')
|
||||
(ROOT / 'evidence/pipeline-invariants.json').write_text(json.dumps(results, indent=2) + '\n')
|
||||
print(json.dumps(results, indent=2), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', '--wait', 'worker')
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Submit synthetic attachments without waiting for worker; no credentials printed."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
|
||||
client = Client()
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
for _ in range(3):
|
||||
attachment, _ = client.attachment(actor, chat)
|
||||
print('accepted attachment:', attachment['id'])
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Запрет БД только для api-a через pg_hba; восстановление в finally."""
|
||||
import ipaddress
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d",
|
||||
"messenger", "-v", "ON_ERROR_STOP=1", "-Atc", statement)
|
||||
|
||||
|
||||
def ready(service):
|
||||
code = """import urllib.request, urllib.error
|
||||
try:
|
||||
print(urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=7).status)
|
||||
except urllib.error.HTTPError as error:
|
||||
print(error.code)
|
||||
"""
|
||||
return compose("exec", "-T", service, "/app/.venv/bin/python", "-c", code)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client()
|
||||
container = json.loads(subprocess.check_output(
|
||||
["docker", "inspect", compose("ps", "-q", "api-a")], text=True))[0]
|
||||
addresses = list(container["NetworkSettings"]["Networks"].values())
|
||||
check(len(addresses) == 1, "test expects one API network")
|
||||
address = str(ipaddress.IPv4Address(addresses[0]["IPAddress"]))
|
||||
bad_id = container["Config"]["Hostname"]
|
||||
before = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(40)}
|
||||
check(len(before) == 2 and bad_id in before, "both API replicas must be reachable")
|
||||
check(ready("api-a") == ready("api-b") == "200", "both APIs must be ready")
|
||||
# Сохраняем исходный pg_hba; чужую оставшуюся резервную копию не перезаписываем.
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'test ! -e "$PGDATA/pg_hba.conf.readiness-backup"; '
|
||||
'cp -p "$PGDATA/pg_hba.conf" "$PGDATA/pg_hba.conf.readiness-backup"')
|
||||
try:
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'{ printf "host all all %s/32 reject\\n" "$1"; '
|
||||
'cat "$PGDATA/pg_hba.conf.readiness-backup"; } > "$PGDATA/pg_hba.conf"',
|
||||
"sh", address)
|
||||
sql("SELECT pg_reload_conf()")
|
||||
time.sleep(0.5)
|
||||
sql(f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE client_addr = '{address}'::inet")
|
||||
check(ready("api-a") == "503", "api-a must be unready")
|
||||
check(ready("api-b") == "200", "api-b must remain ready")
|
||||
# 2s interval + 2s check timeout, с запасом на планировщик Docker Desktop.
|
||||
time.sleep(6)
|
||||
for _ in range(40):
|
||||
result = client.call("GET", "/health/live", 200)
|
||||
check(result["headers"]["X-Instance-Id"] != bad_id, "LB selected unready api-a")
|
||||
for _ in range(20):
|
||||
result = client.call("POST", "/api/v1/users", 201, body={
|
||||
"username": "r_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Readiness regression",
|
||||
"password": "Test-password-" + uuid.uuid4().hex,
|
||||
}, schema="User")
|
||||
check(result["headers"]["X-Instance-Id"] != bad_id, "registration reached api-a")
|
||||
print("PASS: api-a ready=503, api-b ready=200; 40/40 live and 20/20 registrations use api-b")
|
||||
finally:
|
||||
compose("exec", "-T", "postgres", "sh", "-ec",
|
||||
'mv "$PGDATA/pg_hba.conf.readiness-backup" "$PGDATA/pg_hba.conf"')
|
||||
sql("SELECT pg_reload_conf()")
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
observed = {client.call("GET", "/health/live")["headers"]["X-Instance-Id"] for _ in range(10)}
|
||||
if observed == before:
|
||||
check(ready("api-a") == "200", "restored api-a must be ready")
|
||||
print("PASS: database access restored; both API replicas returned to LB")
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise AssertionError("api-a did not return to LB")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка 503 readiness при остановленном PostgreSQL."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
Client().call("GET", "/health/ready", 503)
|
||||
print("PASS: readiness rejects unavailable PostgreSQL")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject S3/DB disagreement and prove dry-run, grace period and safe repair."""
|
||||
import json
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None, env=None) -> str:
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
|
||||
input=input, env=env)
|
||||
|
||||
|
||||
def reconcile(*args) -> dict:
|
||||
output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile", *args)
|
||||
return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{")))
|
||||
|
||||
|
||||
def s3_code(action: str, key: str, data: bytes | None = None) -> None:
|
||||
code = """from src.storage.s3 import S3Settings, S3Store
|
||||
import base64, json, sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
payload = json.load(sys.stdin)
|
||||
key = payload['key']
|
||||
try:
|
||||
if sys.argv[1] == 'put':
|
||||
s3.client.put_object(Bucket=s3.settings.bucket, Key=key,
|
||||
Body=base64.b64decode(payload.get('data', 'b3JwaGFu')))
|
||||
else:
|
||||
s3.client.delete_object(Bucket=s3.settings.bucket, Key=key)
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
payload = {"key": key}
|
||||
if data is not None:
|
||||
payload["data"] = base64.b64encode(data).decode()
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action,
|
||||
input=json.dumps(payload))
|
||||
|
||||
|
||||
def wait_ready(client: Client, env=None) -> None:
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "stack did not recover")
|
||||
time.sleep(.5)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
image = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
|
||||
def upload(name, expected=201):
|
||||
return client.call("POST", path + name, expected, actor=alice, raw=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
|
||||
# A reference object must survive an apply sweep, even with zero grace.
|
||||
protected = upload("protected.png")["json"]
|
||||
message = client.message(alice, chat, "protected", attachments=[protected["id"]])["json"]
|
||||
orphan = "originals/test-orphan-" + uuid.uuid4().hex
|
||||
s3_code("put", orphan)
|
||||
|
||||
report = reconcile("--grace-seconds", "3600")
|
||||
check(orphan in report["fresh_unreferenced"], "fresh orphan missing from dry-run")
|
||||
check(not report["deleted"], "dry-run deleted an object")
|
||||
report = reconcile("--apply", "--grace-seconds", "3600", "--object-key", orphan)
|
||||
check(orphan in report["fresh_unreferenced"] and not report["deleted"], "grace period ignored")
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
|
||||
check(report["deleted"] == [orphan], "aged orphan was not deleted safely")
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", orphan)
|
||||
check(orphan not in report["deleted"] and orphan not in report["orphan_candidates"],
|
||||
"second repair run was not idempotent")
|
||||
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"reconciler deleted a referenced object")
|
||||
|
||||
# This models loss after metadata has committed: report it, do not delete metadata.
|
||||
missing = upload("missing.png")["json"]
|
||||
missing_key = "originals/" + missing["id"]
|
||||
s3_code("delete", missing_key)
|
||||
try:
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", missing_key)
|
||||
expected = {"attachment_id": missing["id"], "object_key": missing_key}
|
||||
check(expected in report["missing_objects"], "missing metadata/object pair not reported")
|
||||
client.call("GET", "/api/v1/attachments/" + missing["id"], actor=bob, schema="Attachment")
|
||||
client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 503, actor=bob)
|
||||
finally:
|
||||
s3_code("put", missing_key, image)
|
||||
check(client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"test object was not restored")
|
||||
report = reconcile("--grace-seconds", "0")
|
||||
check(expected not in report["missing_objects"], "restored object remained missing on second scan")
|
||||
print("PASS: S3-side missing object, dry-run, grace period and idempotent orphan repair", flush=True)
|
||||
|
||||
# Inject a process-equivalent failure after PUT directly into the configured
|
||||
# replica. The public load balancer may correctly select the healthy peer,
|
||||
# which would not exercise this boundary.
|
||||
environment = dict(__import__("os").environ, UPLOAD_FAULT_AFTER_S3_PUT="1")
|
||||
before_fault = set(reconcile("--grace-seconds", "0")["orphan_candidates"])
|
||||
try:
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
|
||||
wait_ready(client, environment)
|
||||
fault = """import base64, json, sys, urllib.error, urllib.request
|
||||
payload = json.load(sys.stdin)
|
||||
request = urllib.request.Request('http://127.0.0.1:8080/api/v1/chats/' + payload['chat_id'] +
|
||||
'/attachments?filename=fault-after-put.png', data=base64.b64decode(payload['image']),
|
||||
method='POST', headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
|
||||
try:
|
||||
urllib.request.urlopen(request, timeout=30)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503, error.code
|
||||
assert json.load(error)['error']['code'] == 'unavailable'
|
||||
else:
|
||||
raise AssertionError('fault injection unexpectedly returned success')
|
||||
"""
|
||||
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", fault,
|
||||
input=json.dumps({"chat_id": chat["id"], "token": alice["token"],
|
||||
"image": base64.b64encode(image).decode()}))
|
||||
report = reconcile("--grace-seconds", "0")
|
||||
injected = sorted(set(report["orphan_candidates"]) - before_fault)
|
||||
check(len(injected) == 1, "fault must create exactly one new orphan; run without other writers")
|
||||
report = reconcile("--apply", "--grace-seconds", "0", "--object-key", injected[0])
|
||||
check(set(injected).issubset(report["deleted"]), "reconciler did not clean injected orphan")
|
||||
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]
|
||||
check(message in history["items"], "message reference was lost")
|
||||
check(client.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=bob)["bytes"] == image,
|
||||
"used original was lost")
|
||||
print("PASS: injected pre-INSERT failure repaired; message and used original survive", flush=True)
|
||||
finally:
|
||||
environment["UPLOAD_FAULT_AFTER_S3_PUT"] = "0"
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--wait", "--force-recreate", "--no-deps", "api-a"],
|
||||
cwd=ROOT, env=environment, check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real database rejection, concurrent commit, interrupted upload and pagination."""
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, run
|
||||
|
||||
PROBE = r'''
|
||||
import asyncio, base64, hashlib, http.client, json, sys, urllib.request, urllib.error
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID, uuid4
|
||||
from src.config import load_settings
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.storage.s3 import S3Store, S3Settings
|
||||
from src.reconcile import run as reconcile, scan
|
||||
|
||||
payload = json.load(sys.stdin)
|
||||
image = base64.b64decode(payload['image'])
|
||||
chat_id, user_id = UUID(payload['chat_id']), UUID(payload['user_id'])
|
||||
|
||||
def upload(filename):
|
||||
req = urllib.request.Request('http://api-a:8080/api/v1/chats/' + str(chat_id) +
|
||||
'/attachments?filename=' + filename, data=image, method='POST',
|
||||
headers={'Authorization': 'Bearer ' + payload['token'], 'Content-Type': 'image/png'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as response:
|
||||
return response.status, json.load(response)
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, json.load(error)
|
||||
|
||||
async def main():
|
||||
db = PostgresStore(load_settings().database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
await db.connect()
|
||||
def args(key):
|
||||
return SimpleNamespace(apply=True, grace_seconds=0, object_key=[key])
|
||||
try:
|
||||
# A failed metadata inventory must not authorize any S3 deletion.
|
||||
key = 'originals/audit-inventory-' + uuid4().hex
|
||||
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
|
||||
class BrokenInventory:
|
||||
async def attachment_keys(self):
|
||||
# Real SQL failure, not an empty inventory on error.
|
||||
return await db.pool.fetch('SELECT * FROM audit_missing_table_' + uuid4().hex)
|
||||
try:
|
||||
async with db.attachment_transaction(maintenance=True):
|
||||
try:
|
||||
await scan(args(key), BrokenInventory(), s3)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('failed inventory did not abort')
|
||||
assert key in await s3.list('originals/')
|
||||
finally:
|
||||
await s3.delete(key)
|
||||
print('PASS: failed PostgreSQL inventory aborts apply without deleting the orphan', flush=True)
|
||||
|
||||
# An actual PostgreSQL trigger rejects only this test chat's INSERT.
|
||||
suffix = uuid4().hex
|
||||
name = 'audit_reject_' + suffix
|
||||
before = await s3.list('originals/')
|
||||
await db.pool.execute(f"""CREATE FUNCTION {name}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN IF NEW.chat_id = '{chat_id}'::uuid THEN
|
||||
RAISE EXCEPTION 'synthetic audit rejection' USING ERRCODE = '23514';
|
||||
END IF; RETURN NEW; END $$""")
|
||||
try:
|
||||
await db.pool.execute(f'CREATE TRIGGER {name} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {name}()')
|
||||
status, body = await asyncio.to_thread(upload, 'db-failure.png')
|
||||
assert status == 503 and body['error']['code'] == 'unavailable', (status, body)
|
||||
assert await db.pool.fetchval('SELECT count(*) FROM attachments WHERE chat_id=$1', chat_id) == 0
|
||||
finally:
|
||||
await db.pool.execute(f'DROP TRIGGER IF EXISTS {name} ON attachments')
|
||||
await db.pool.execute(f'DROP FUNCTION {name}()')
|
||||
created = set(await s3.list('originals/')) - set(before)
|
||||
assert len(created) == 1, created
|
||||
key = created.pop()
|
||||
report = await reconcile(SimpleNamespace(apply=False, grace_seconds=0, object_key=[key]))
|
||||
assert key in report['orphan_candidates'] and not report['deleted']
|
||||
assert (await reconcile(args(key)))['deleted'] == [key]
|
||||
assert not (await reconcile(args(key)))['deleted']
|
||||
print('PASS: actual PostgreSQL INSERT rejection -> 503, dry-run detection, scoped repair, repeat no-op', flush=True)
|
||||
|
||||
# Writer holds a shared lock after PUT; cleanup must wait for COMMIT.
|
||||
identifier = uuid4()
|
||||
key = 'originals/' + str(identifier)
|
||||
async with db.attachment_transaction() as connection:
|
||||
await s3.call('put_object', Bucket=s3.settings.bucket, Key=key, Body=image)
|
||||
sweep = asyncio.create_task(reconcile(args(key)))
|
||||
for _ in range(40):
|
||||
waiting = await db.pool.fetchval("SELECT count(*) FROM pg_locks WHERE locktype='advisory' AND classid=41004 AND objid=1 AND NOT granted")
|
||||
if waiting:
|
||||
break
|
||||
await asyncio.sleep(.05)
|
||||
assert waiting and not sweep.done(), 'maintenance failed to wait for active writer'
|
||||
await db.create_attachment(identifier, chat_id, user_id, 'concurrent.png', 'image/png',
|
||||
len(image), hashlib.sha256(image).hexdigest(), key, connection=connection)
|
||||
report = await sweep
|
||||
assert key not in report['deleted'] and key not in report['orphan_candidates']
|
||||
row = await db.attachment_for_member(identifier, user_id)
|
||||
assert await s3.download(row) == image
|
||||
print('PASS: apply with zero grace waits for in-flight PUT/COMMIT; committed original survives', flush=True)
|
||||
|
||||
# Abrupt client close before all bytes arrive must not persist a file.
|
||||
before = await s3.list('originals/')
|
||||
rows = await db.attachment_keys()
|
||||
def interrupt():
|
||||
conn = http.client.HTTPConnection('api-a', 8080, timeout=10)
|
||||
conn.putrequest('POST', '/api/v1/chats/' + str(chat_id) + '/attachments?filename=interrupted.png')
|
||||
conn.putheader('Authorization', 'Bearer ' + payload['token'])
|
||||
conn.putheader('Content-Type', 'image/png')
|
||||
conn.putheader('Content-Length', str(len(image) + 100000))
|
||||
conn.endheaders()
|
||||
conn.send(image[:32])
|
||||
conn.close()
|
||||
await asyncio.to_thread(interrupt)
|
||||
await asyncio.sleep(1)
|
||||
assert await db.attachment_keys() == rows
|
||||
assert await s3.list('originals/') == before
|
||||
status, body = await asyncio.to_thread(upload, 'after-disconnect.png')
|
||||
assert status == 201, (status, body)
|
||||
print('PASS: interrupted upload leaves no metadata/object and next upload succeeds', flush=True)
|
||||
|
||||
# Exercise pagination on real S3 without adding thousands of fixtures.
|
||||
original_call = s3.call
|
||||
async def small_pages(method, **kwargs):
|
||||
if method == 'list_objects_v2':
|
||||
kwargs['MaxKeys'] = 7
|
||||
return await original_call(method, **kwargs)
|
||||
expected = await s3.list('originals/')
|
||||
s3.call = small_pages
|
||||
actual, pages = await s3.list_with_pages('originals/')
|
||||
assert actual == expected and pages > 1
|
||||
print(f'PASS: S3 pagination: {len(actual)} keys across {pages} pages, no missing/duplicate keys', flush=True)
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
|
||||
asyncio.run(main())
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
payload = {"chat_id": chat["id"], "user_id": alice["id"], "token": alice["token"],
|
||||
"image": base64.b64encode((ROOT / "tests/fixtures/sample.png").read_bytes()).decode()}
|
||||
subprocess.run(["docker", "compose", "--profile", "maintenance", "run", "--rm", "--no-deps",
|
||||
"--entrypoint", "/app/.venv/bin/python", "reconcile", "-c", PROBE],
|
||||
cwd=ROOT, input=json.dumps(payload), text=True, check=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure repeatable reconciler inventory cost for two controlled S3 sizes."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None) -> str:
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, input=input)
|
||||
|
||||
|
||||
def reconcile() -> dict:
|
||||
output = compose("--profile", "maintenance", "run", "--rm", "--no-deps", "reconcile",
|
||||
"--grace-seconds", "3600")
|
||||
return json.loads(next(line for line in reversed(output.splitlines()) if line.startswith("{")))
|
||||
|
||||
|
||||
def mutate(action: str, keys: list[str]) -> None:
|
||||
code = """from src.storage.s3 import S3Settings, S3Store
|
||||
import json, sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
for key in json.load(sys.stdin):
|
||||
if sys.argv[1] == 'put':
|
||||
s3.client.put_object(Bucket=s3.settings.bucket, Key=key, Body=b'track-2-benchmark')
|
||||
else:
|
||||
s3.client.delete_object(Bucket=s3.settings.bucket, Key=key)
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", code, action,
|
||||
input=json.dumps(keys))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
arguments(__doc__) # Keeps the common --base-url/--ca-file command interface.
|
||||
results = []
|
||||
for requested in (32, 128):
|
||||
prefix = f"originals/track2-benchmark-{uuid.uuid4().hex}-"
|
||||
keys = [prefix + str(index) for index in range(requested)]
|
||||
try:
|
||||
mutate("put", keys)
|
||||
reports = [reconcile() for _ in range(3)]
|
||||
for report in reports:
|
||||
check(set(keys).issubset(report["fresh_unreferenced"]),
|
||||
"benchmark objects were not included in the inventory")
|
||||
check(not set(keys) & set(report["orphan_candidates"]),
|
||||
"grace period classified fresh benchmark objects as deletable")
|
||||
seconds = [report["scan_metrics"]["total_seconds"] for report in reports]
|
||||
results.append({
|
||||
"added_unreferenced_objects": requested,
|
||||
"runs": 3,
|
||||
"s3_objects_scanned": reports[-1]["s3_objects"],
|
||||
"metadata_rows_scanned": reports[-1]["metadata_rows"],
|
||||
"s3_list_pages": reports[-1]["scan_metrics"]["s3_list_pages"],
|
||||
"seconds": seconds,
|
||||
"median_seconds": round(statistics.median(seconds), 6),
|
||||
})
|
||||
finally:
|
||||
mutate("delete", keys)
|
||||
print(json.dumps({"method": "three dry-run inventories per controlled size", "results": results},
|
||||
sort_keys=True))
|
||||
print("PASS: reconciler cost measured for 32 and 128 added S3 objects; fixtures removed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Contract, isolated-render and benchmark regressions without Docker."""
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import importlib.util
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from PIL import Image
|
||||
from src.worker import variants, render_isolated, PermanentFailure
|
||||
from src.storage.postgres import PostgresStore
|
||||
from src.reconcile import scan
|
||||
from src.errors import ApiError
|
||||
|
||||
|
||||
def png(width, height):
|
||||
buffer = BytesIO()
|
||||
Image.new('RGBA', (width, height), (255, 0, 0, 0)).save(buffer, 'PNG')
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class Regressions(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_failed_attachment_is_rejected(self):
|
||||
store, connection = PostgresStore('unused'), AsyncMock()
|
||||
connection.fetchval.side_effect = [1, 1, 1]
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
with self.assertRaises(ApiError) as error:
|
||||
await store.create_message_idempotent(uuid4(), uuid4(), '', 'key', 86400, [uuid4()])
|
||||
self.assertEqual(error.exception.status_code, 409)
|
||||
connection.fetchrow.assert_not_awaited()
|
||||
|
||||
def test_floor_and_small_images(self):
|
||||
self.assertEqual(variants(png(300, 200))[0][3:], (256, 170))
|
||||
self.assertEqual(variants(png(200, 300))[0][3:], (170, 256))
|
||||
self.assertEqual(variants(png(10, 8))[0][3:], (10, 8))
|
||||
for name, data, mime, width, height in variants(png(300, 200)):
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
self.assertEqual(image.size, (width, height))
|
||||
self.assertTrue(all(value > 240 for value in image.convert('RGB').getpixel((0, 0))))
|
||||
|
||||
def test_renderer_success_and_permanent_error(self):
|
||||
self.assertEqual(render_isolated(png(300, 200), 10)[0][3:], (256, 170))
|
||||
with self.assertRaises(PermanentFailure):
|
||||
render_isolated(b'not an image', 10)
|
||||
|
||||
def test_renderer_is_killed_on_deadline(self):
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(TimeoutError):
|
||||
render_isolated(png(300, 200), .0001)
|
||||
self.assertLess(time.monotonic() - started, 2)
|
||||
|
||||
async def test_cleanup_retains_active_and_failed_staging(self):
|
||||
old = datetime.now(timezone.utc) - timedelta(days=2)
|
||||
db, s3 = AsyncMock(), AsyncMock()
|
||||
db.attachment_keys.return_value = {'staging/active': uuid4(), 'staging/failed': uuid4(), 'originals/ready': uuid4()}
|
||||
s3.list_with_pages.side_effect = [({'staging/active': old, 'staging/failed': old, 'staging/orphan': old}, 1),
|
||||
({'originals/ready': old}, 1), ({'variants/orphan': old}, 1)]
|
||||
report = await scan(SimpleNamespace(grace_seconds=60, apply=True, object_key=[]), db, s3)
|
||||
self.assertEqual(report['deleted'], ['staging/orphan', 'variants/orphan'])
|
||||
|
||||
async def test_permanent_failure_is_atomic_and_not_retried(self):
|
||||
store = PostgresStore('unused')
|
||||
connection = AsyncMock()
|
||||
connection.fetchrow.return_value = {'attempt': 1}
|
||||
@asynccontextmanager
|
||||
async def context():
|
||||
yield connection
|
||||
connection.transaction = context
|
||||
store._pool = SimpleNamespace(acquire=context)
|
||||
result = await store.retry_attachment_job(uuid4(), 5, 1, datetime.now(timezone.utc), 'invalid_image')
|
||||
self.assertFalse(result)
|
||||
self.assertEqual(connection.execute.await_count, 2)
|
||||
for call in connection.execute.call_args_list:
|
||||
self.assertIn("status='failed'", call.args[0])
|
||||
self.assertEqual(call.args[2], 'invalid_image')
|
||||
|
||||
def test_benchmark_partial_batch_and_recovery(self):
|
||||
spec = importlib.util.spec_from_file_location('track1', ROOT / 'scripts/track1.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
jobs, lock = {}, threading.Lock()
|
||||
class FakeClient:
|
||||
def __init__(self, *args, **kwargs): pass
|
||||
def bootstrap(self): return {}, {}, {}, {'id': str(uuid4())}
|
||||
def call(self, method, path, *args, **kwargs):
|
||||
if method == 'POST':
|
||||
key = str(uuid4())
|
||||
with lock: jobs[key] = {'id': key, 'status': 'ready', 'queue_wait_seconds': .01}
|
||||
return {'status': 202, 'json': {'id': key}}
|
||||
return {'json': {'status': 'ready'}}
|
||||
def attachment(self, *args): return {}, b''
|
||||
def wait_ready(self, *args, **kwargs): return {}
|
||||
def metrics(_):
|
||||
with lock:
|
||||
return {'jobs': list(jobs.values()), 'pending': 0, 'rss_bytes': 1000, 'concurrency': 2, 'prefetch': 2}
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
destination = str(Path(directory) / 'result.json')
|
||||
args = SimpleNamespace(run_name='test', workers=2, prefetch=2, max_pending=20, images=10,
|
||||
concurrency=8, size=8, max_ready_seconds=2, require_backpressure=False,
|
||||
output=destination, base_url=None, ca_file=None)
|
||||
info = {'Config': {'Env': ['MAX_PENDING_JOBS=20']}, 'HostConfig': {'Memory': 4096, 'NanoCpus': 2}}
|
||||
with patch.object(module, 'arguments', return_value=args), patch.object(module, 'Client', FakeClient), \
|
||||
patch.object(module, 'metrics', side_effect=metrics), patch.object(module, 'container_info', return_value=info), \
|
||||
patch.object(module, 'broker_depth', return_value={'messages_ready': 0, 'messages_unacknowledged': 0}):
|
||||
module.main()
|
||||
report = json.loads(Path(destination).read_text())
|
||||
self.assertEqual(report['results']['ready'], 10)
|
||||
self.assertTrue(report['results']['recovery_upload_ready'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Crash one idle lab worker after S3 writes; restore normal configuration in finally."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def compose(*args, env=None):
|
||||
return subprocess.run(['docker','compose',*args],cwd=ROOT,env=env,check=True,capture_output=True,text=True).stdout
|
||||
count=compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')")
|
||||
if int(count.strip()):raise RuntimeError('Pending work; refusing crash injection')
|
||||
try:
|
||||
compose('stop','-t','5','worker')
|
||||
compose('up','-d','--no-deps','worker',env={**os.environ,'WORKER_FAULT_AFTER_S3_PUT':'1'})
|
||||
subprocess.run([sys.executable,'student-tests/trace_retry.py'],cwd=ROOT,check=True,timeout=180)
|
||||
out=json.loads((ROOT/'evidence/review-retry-job.json').read_text())
|
||||
from uuid import UUID
|
||||
identity=str(UUID(out['attachment_id']))
|
||||
out['db_attempt']=int(compose('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',f"SELECT attempt FROM attachment_jobs WHERE attachment_id='{identity}'").strip())
|
||||
cid=compose('ps','-q','worker').strip()
|
||||
out['restart_count']=int(subprocess.run(['docker','inspect','--format','{{.RestartCount}}',cid],check=True,capture_output=True,text=True).stdout.strip())
|
||||
assert out['db_attempt']==2 and out['restart_count']==1,out
|
||||
(ROOT/'evidence/review-retry-job.json').write_text(json.dumps(out,indent=2)+'\n')
|
||||
time.sleep(10)
|
||||
subprocess.run([sys.executable,'student-tests/capture_observability.py','--trace-id',out['trace_id'],'--output','evidence/review-retry-trace.json'],cwd=ROOT,check=True)
|
||||
finally:
|
||||
compose('stop','-t','5','worker')
|
||||
compose('up','-d','--no-deps','worker',env={**os.environ,'WORKER_FAULT_AFTER_S3_PUT':'0'})
|
||||
print('PASS: attempt 2, one restart, normal worker restored')
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Repeat short review checks; experiments are separate and intentionally disruptive."""
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
checks=[['make','check'],['make','validate','PYTHON=.venv/bin/python'],
|
||||
['docker','compose','config','--quiet'],
|
||||
['docker','run','--rm','-v',f'{ROOT}:/workspace:ro','--entrypoint','promtool','prom/prometheus:v3.2.1','test','rules',
|
||||
'/workspace/student-tests/alerts.test.yaml','/workspace/student-tests/burn_rules.test.yaml','/workspace/student-tests/telemetry_alerts.test.yaml'],
|
||||
['make','test'],['python3','student-tests/check_dashboard.py']]
|
||||
results=[]
|
||||
for command in checks:
|
||||
proc=subprocess.run(command,cwd=ROOT,capture_output=True,text=True,timeout=180)
|
||||
results.append({'command':command,'exit_code':proc.returncode,'output':proc.stdout+proc.stderr})
|
||||
for filename in ('telemetry_unit.py','pipeline_critical.py','slo_commit_integration.py'):
|
||||
command=['docker','compose','exec','-T','api-a','/app/.venv/bin/python','-']
|
||||
proc=subprocess.run(command,input=(ROOT/'student-tests'/filename).read_text(),cwd=ROOT,capture_output=True,text=True,timeout=60)
|
||||
results.append({'command':command,'stdin':f'student-tests/{filename}','exit_code':proc.returncode,'output':proc.stdout+proc.stderr})
|
||||
(ROOT/'evidence/review-checks.json').write_text(json.dumps({'utc':datetime.now(timezone.utc).isoformat(),'checks':results},ensure_ascii=False,indent=2)+'\n')
|
||||
for r in results:print('PASS' if r['exit_code']==0 else 'FAIL',r.get('stdin',r['command']))
|
||||
raise SystemExit(any(r['exit_code'] for r in results))
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Read current health of telemetry, without printing access credentials."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('capture',ROOT/'student-tests/capture_observability.py')
|
||||
c=importlib.util.module_from_spec(spec);spec.loader.exec_module(c)
|
||||
queries=['messenger_slo_unknown{service_name="messenger-outbox"}',
|
||||
'time()-max(messenger_queue_sample_time_seconds{service_name="messenger-outbox"})',
|
||||
'messenger_queue_depth{service_name="messenger-outbox"}',
|
||||
'messenger_job_ready_duration_seconds_count{service_name="messenger-worker"}']
|
||||
for q in queries:
|
||||
print(q,json.dumps(c.get('prometheus','api/v1/query',{'query':q})['data']['result']))
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Регрессии ревью: не-ASCII Bearer и невалидная кодировка JSON через LB."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
for path in ("/api/v1/users/me", "/api/v1/auth/sessions/current"):
|
||||
method = "DELETE" if path.endswith("/current") else "GET"
|
||||
result = client.call(method, path, 401,
|
||||
headers={"Authorization": "Bearer é"}, schema="Error")
|
||||
check(result["headers"].get("WWW-Authenticate", "").startswith("Bearer"),
|
||||
"missing Bearer challenge")
|
||||
check(result["json"]["error"]["code"] == "unauthorized", "wrong error code")
|
||||
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
|
||||
"request IDs differ")
|
||||
for raw in (b"\xff", b"{", b'{"username":'):
|
||||
result = client.call("POST", "/api/v1/users", 400, raw=raw,
|
||||
headers={"Content-Type": "application/json"}, schema="Error")
|
||||
check(result["json"]["error"]["code"] == "invalid_request", "wrong JSON error code")
|
||||
check(result["json"]["error"]["request_id"] == result["headers"]["X-Request-Id"],
|
||||
"request IDs differ")
|
||||
print("PASS: non-ASCII Bearer returns 401/challenge; malformed JSON returns contract Error/400")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Run inherited public durability/failover checks and restore both API replicas."""
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
results=[]
|
||||
try:
|
||||
for command in [
|
||||
['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh'],
|
||||
['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh']]:
|
||||
result=subprocess.run(command,cwd=ROOT,capture_output=True,text=True,timeout=240)
|
||||
results.append({'command':command,'exit_code':result.returncode,'output':result.stdout+result.stderr})
|
||||
print('PASS' if result.returncode==0 else 'FAIL',command,flush=True)
|
||||
if result.returncode:break
|
||||
finally:
|
||||
restore=subprocess.run(['docker','compose','up','-d','--no-deps','--wait','api-a','api-b','worker','outbox'],cwd=ROOT,capture_output=True,text=True,timeout=90)
|
||||
results.append({'restore_exit_code':restore.returncode,'output':restore.stdout+restore.stderr})
|
||||
(ROOT/'evidence/review-resilience.json').write_text(json.dumps({'utc':datetime.now(timezone.utc).isoformat(),'checks':results},ensure_ascii=False,indent=2)+'\n')
|
||||
raise SystemExit(any(r.get('exit_code',r.get('restore_exit_code')) for r in results))
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove that the API identity is bucket-scoped and lacks admin operations."""
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True,
|
||||
input=input, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
data = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=permission.png", 202,
|
||||
actor=alice, raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
bucket = "permission-probe-" + uuid.uuid4().hex
|
||||
code = """from botocore.exceptions import ClientError
|
||||
from src.storage.s3 import S3Settings, S3Store
|
||||
import sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
try:
|
||||
s3.client.create_bucket(Bucket=sys.stdin.read().strip())
|
||||
except ClientError as error:
|
||||
assert error.response['Error']['Code'] in {'AccessDenied', 'Unauthorized'}, error.response
|
||||
else:
|
||||
raise AssertionError('API S3 identity unexpectedly has admin bucket creation')
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("exec", "-T", "api-a", "/app/.venv/bin/python", "-c", code, input=bucket)
|
||||
admin = """from src.storage.s3 import S3Settings, S3Store
|
||||
import sys
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
s3.client.list_buckets()
|
||||
finally:
|
||||
s3.client.close()
|
||||
"""
|
||||
compose("run", "--rm", "--no-deps", "s3-init", "/app/.venv/bin/python", "-c", admin)
|
||||
print("PASS: API identity cannot create buckets; maintenance identity has separate admin access")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка expiry; запускается при SESSION_TTL_SECONDS=2."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client()
|
||||
actor = client.user("expiry")
|
||||
time.sleep(3)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS: expired Bearer session was rejected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize observed alert transitions; sampling bounds detection precision."""
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
data = json.loads((root / 'evidence/slo-incidents.json').read_text())
|
||||
samples = sorted((s for s in data['samples'] if 'firing' in s), key=lambda s: s['monotonic'])
|
||||
alerts = ['MessengerApiBurnFast', 'MessengerApiBurnSlow']
|
||||
output = {'sampling_interval_seconds': 5, 'monitor_errors': sum('monitor_error' in s for s in data['samples']), 'phases': {}}
|
||||
drifts = [abs((datetime.fromisoformat(b['time']) - datetime.fromisoformat(a['time'])).total_seconds()
|
||||
- (b['monotonic'] - a['monotonic'])) for a, b in zip(samples, samples[1:])]
|
||||
gaps = [b['monotonic'] - a['monotonic'] for a, b in zip(samples, samples[1:])]
|
||||
output['timing_quality'] = {'max_wall_monotonic_disagreement_seconds': round(max(drifts, default=0), 3),
|
||||
'max_observed_sampling_gap_seconds': round(max(gaps, default=0), 3),
|
||||
'valid_for_elapsed_time_claims': max(drifts, default=0) <= 1,
|
||||
'note': 'Disagreement does not identify its cause; rerun if invalid. Precision is bounded by actual gaps, not the configured sleep.'}
|
||||
base = [s for s in samples if s['phase'] == 'baseline']
|
||||
output['baseline'] = {'samples': len(base), 'samples_with_burn_alert': sum(bool(s['firing']) for s in base), 'scope': 'one observed healthy baseline, not a long-term false-positive rate'}
|
||||
for name, period in data['periods'].items():
|
||||
start, end = period['lock_observed']['monotonic'], period['command_completed']['monotonic']
|
||||
active = [s for s in samples if start <= s['monotonic'] <= end]
|
||||
recovery = [s for s in samples if s['monotonic'] > end and s['phase'] == name + '_recovery']
|
||||
previous = [s for s in samples if s['monotonic'] < start]
|
||||
row = {'observed_lock_seconds': round(end-start, 3), 'alerts': {}}
|
||||
for alert in alerts:
|
||||
before = bool(previous and alert in previous[-1]['firing'])
|
||||
hits = [s for s in active + recovery if alert in s['firing']]
|
||||
clear = [s for s in recovery if hits and s['monotonic'] > hits[0]['monotonic'] and alert not in s['firing']]
|
||||
row['alerts'][alert] = {'active_before_lock': before,
|
||||
'first_firing': hits[0]['time'] if hits else None,
|
||||
'first_firing_after_incident': bool(hits and hits[0]['monotonic'] > end),
|
||||
'detection_seconds': round(hits[0]['monotonic']-start, 3) if hits and not before else None,
|
||||
'first_clear': clear[0]['time'] if hits and clear else None,
|
||||
'recovery_seconds': round(clear[0]['monotonic']-end, 3) if hits and clear else None}
|
||||
output['phases'][name] = row
|
||||
path = root / 'evidence/slo-analysis.json'
|
||||
path.write_text(json.dumps(output, ensure_ascii=False, indent=2) + '\n')
|
||||
print(json.dumps(output, ensure_ascii=False, indent=2))
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Run inside api-a; session-local table shadows real SLO data (no business mutations)."""
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from uuid import uuid4
|
||||
import asyncpg
|
||||
from src.config import load_settings
|
||||
from src.storage.postgres import PostgresStore
|
||||
|
||||
async def main():
|
||||
store = PostgresStore(load_settings().database_url)
|
||||
store._pool = await asyncpg.create_pool(load_settings().database_url, min_size=1, max_size=1)
|
||||
try:
|
||||
async with store.pool.acquire() as conn:
|
||||
await conn.execute('CREATE TEMP TABLE attachment_slo (LIKE public.attachment_slo INCLUDING DEFAULTS)')
|
||||
identity = uuid4()
|
||||
async with conn.transaction():
|
||||
await conn.execute('INSERT INTO attachment_slo (attachment_id) VALUES ($1)', identity)
|
||||
await asyncio.sleep(.2)
|
||||
before_accept_commit = await conn.fetchval('SELECT clock_timestamp()')
|
||||
async with conn.transaction():
|
||||
await conn.execute('UPDATE attachment_slo SET ready_xid=pg_current_xact_id()::xid')
|
||||
await asyncio.sleep(.2)
|
||||
before_ready_commit = await conn.fetchval('SELECT clock_timestamp()')
|
||||
await store.sample_ready_slo()
|
||||
row = await store.pool.fetchrow('SELECT * FROM attachment_slo')
|
||||
assert row['accepted_at'] >= before_accept_commit
|
||||
assert row['ready_at'] >= before_ready_commit
|
||||
elapsed = await store.ready_seconds(identity)
|
||||
assert elapsed >= .2, elapsed
|
||||
# Mature a successful synthetic cohort, then emulate replay metadata changes.
|
||||
await store.pool.execute("UPDATE attachment_slo SET accepted_at=now()-interval '32 seconds',ready_at=now()-interval '31 seconds'")
|
||||
first = dict(await store.sample_ready_slo())
|
||||
assert first == {'eligible': 1, 'bad': 0, 'unknown': 0}, first
|
||||
await store.pool.execute("UPDATE attachment_slo SET ready_at=now()+interval '1 minute'")
|
||||
assert dict(await store.sample_ready_slo()) == first
|
||||
await store.pool.execute("INSERT INTO attachment_slo (attachment_id,accepted_at) VALUES ($1,now()-interval '31 seconds')", uuid4())
|
||||
late = dict(await store.sample_ready_slo())
|
||||
assert late == {'eligible': 2, 'bad': 1, 'unknown': 0}, late
|
||||
await store.pool.execute('UPDATE attachment_slo SET ready_at=now(),ready_xid=pg_current_xact_id()::xid WHERE ready_at IS NULL')
|
||||
assert dict(await store.sample_ready_slo()) == late
|
||||
print('PASS: commit boundaries; immutable good/bad cohorts; late completion remains bad')
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run two bounded DB-lock incidents against the local Compose project.
|
||||
|
||||
Creates synthetic data, records only aggregate counts/alert states, and releases
|
||||
bounded locks; interrupted server-side sleeps may persist until their deadline. Run on the isolated lab6 stack, never a shared database.
|
||||
"""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure
|
||||
|
||||
OUTPUT = ROOT / 'evidence' / 'slo-incidents.json'
|
||||
STOP = threading.Event()
|
||||
LOCK = threading.Lock()
|
||||
COUNTS = {'ok': 0, 'failed': 0}
|
||||
SCENARIO = {'phase': 'bootstrap'}
|
||||
SAMPLES = []
|
||||
AUTH = 'Basic ' + base64.b64encode(('admin:' + (ROOT / 'secrets/grafana_password').read_text().strip()).encode()).decode()
|
||||
|
||||
def utc(): return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
def get(path, params=None):
|
||||
url = 'http://127.0.0.1:3000/api/datasources/proxy/uid/prometheus/api/v1/' + path
|
||||
if params: url += '?' + urllib.parse.urlencode(params)
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers={'Authorization': AUTH}), timeout=5) as response:
|
||||
result = json.load(response)
|
||||
if result.get('status') != 'success': raise RuntimeError('Prometheus query failed')
|
||||
return result['data']
|
||||
|
||||
def monitor():
|
||||
while not STOP.is_set():
|
||||
try:
|
||||
alerts = get('alerts')['alerts']
|
||||
firing = sorted(a['labels']['alertname'] for a in alerts if a['state'] == 'firing' and 'Burn' in a['labels']['alertname'])
|
||||
with LOCK: sample = {'time': utc(), 'monotonic': time.monotonic(), 'phase': SCENARIO['phase'], 'counts': dict(COUNTS), 'firing': firing, 'all_firing': sorted(a['labels']['alertname'] for a in alerts if a['state'] == 'firing')}
|
||||
SAMPLES.append(sample)
|
||||
except Exception as error:
|
||||
SAMPLES.append({'time': utc(), 'monotonic': time.monotonic(), 'phase': SCENARIO['phase'], 'monitor_error': type(error).__name__})
|
||||
STOP.wait(5)
|
||||
|
||||
def worker(actor, chat):
|
||||
client = Client(timeout=9)
|
||||
while not STOP.is_set():
|
||||
try:
|
||||
client.message(actor, chat, 'synthetic SLO experiment')
|
||||
outcome = 'ok'
|
||||
except Failure:
|
||||
outcome = 'failed'
|
||||
with LOCK: COUNTS[outcome] += 1
|
||||
STOP.wait(1)
|
||||
|
||||
def phase(name):
|
||||
with LOCK: SCENARIO['phase'] = name
|
||||
print(utc(), name, flush=True)
|
||||
|
||||
def db_is_locked():
|
||||
result = subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',
|
||||
"SELECT EXISTS (SELECT 1 FROM pg_locks WHERE relation='users'::regclass AND mode='AccessExclusiveLock' AND granted)"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=10, check=True)
|
||||
return result.stdout.strip() == 't'
|
||||
|
||||
def incident(name, seconds):
|
||||
cmd = ['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-c',
|
||||
f'BEGIN; LOCK TABLE users IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep({seconds}); COMMIT;']
|
||||
start_command = {'time': utc(), 'monotonic': time.monotonic()}
|
||||
proc = subprocess.Popen(cmd, cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
|
||||
try:
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
if proc.poll() is not None: raise RuntimeError('DB lock command ended early')
|
||||
if db_is_locked(): break
|
||||
time.sleep(.5)
|
||||
else: raise RuntimeError('DB lock was not observed')
|
||||
phase(name)
|
||||
start = {'time': utc(), 'monotonic': time.monotonic(), 'command_started': start_command}
|
||||
code = proc.wait(timeout=seconds+20)
|
||||
if code: raise RuntimeError('DB lock command failed')
|
||||
end = {'time': utc(), 'monotonic': time.monotonic()}
|
||||
phase(name + '_recovery')
|
||||
return {'lock_observed': start, 'command_completed': end}
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
try: proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired: proc.kill(); proc.wait()
|
||||
|
||||
def main():
|
||||
client = Client(timeout=9)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
result = {'description': 'controlled DB table lock; three synthetic clients; 5s alert sampling', 'periods': {}, 'samples': SAMPLES}
|
||||
monitor_thread = threading.Thread(target=monitor, daemon=True); monitor_thread.start()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=3) as pool:
|
||||
futures = [pool.submit(worker, actor, chat) for _ in range(3)]
|
||||
try:
|
||||
phase('baseline'); time.sleep(60)
|
||||
result['periods']['burst'] = incident('burst', 75)
|
||||
time.sleep(100)
|
||||
result['periods']['sustained'] = incident('sustained', 180)
|
||||
time.sleep(100)
|
||||
phase('complete')
|
||||
finally:
|
||||
STOP.set()
|
||||
for future in futures: future.result(timeout=15)
|
||||
finally:
|
||||
STOP.set(); monitor_thread.join(timeout=10)
|
||||
result['end_time'] = utc()
|
||||
result['final_counts'] = COUNTS
|
||||
OUTPUT.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
|
||||
print('Aggregate evidence:', OUTPUT, flush=True)
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop only this project's idle worker, submit 8 jobs, verify ready SLO."""
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
|
||||
secret = (ROOT / 'secrets/grafana_password').read_text().strip()
|
||||
auth = 'Basic ' + base64.b64encode(('admin:' + secret).encode()).decode()
|
||||
def utc(): return datetime.now(timezone.utc).isoformat()
|
||||
def prom(path, query=None):
|
||||
url = 'http://127.0.0.1:3000/api/datasources/proxy/uid/prometheus/api/v1/' + path
|
||||
if query is not None: url += '?' + urllib.parse.urlencode({'query': query})
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers={'Authorization': auth}), timeout=5) as r: return json.load(r)['data']
|
||||
def metric(name):
|
||||
result = prom('query', 'max(' + name + '{service_name="messenger-outbox"})')['result']
|
||||
return float(result[0]['value'][1]) if result else None
|
||||
def sample(phase):
|
||||
alerts = prom('alerts')['alerts']
|
||||
return {'time': utc(), 'monotonic': time.monotonic(), 'phase': phase,
|
||||
'firing': sorted(a['labels']['alertname'] for a in alerts if a['state']=='firing' and a['labels']['alertname'].startswith('MessengerReadyBurn')),
|
||||
'all_firing': sorted(a['labels']['alertname'] for a in alerts if a['state']=='firing'),
|
||||
'queue_depth': metric('messenger_queue_depth'), 'queue_age': metric('messenger_queue_age_seconds'),
|
||||
'eligible': metric('messenger_slo_ready_eligible_total'), 'bad': metric('messenger_slo_ready_bad_total')}
|
||||
def docker(*args): subprocess.run(['docker','compose',*args], cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
|
||||
def run():
|
||||
status = subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atc',
|
||||
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')"], cwd=ROOT, check=True, capture_output=True, text=True)
|
||||
if int(status.stdout.strip()): raise RuntimeError('Pending jobs exist; refusing to stop worker')
|
||||
client=Client(); actor,_,_,chat=client.bootstrap(); samples=[]; out={'samples':samples,'jobs':8}
|
||||
worker_stopped=False
|
||||
try:
|
||||
samples.append(sample('baseline'))
|
||||
docker('stop','-t','5','worker'); worker_stopped=True
|
||||
accepted=[]
|
||||
for _ in range(8): accepted.append(client.attachment(actor,chat)[0])
|
||||
out['accepted_at']={'time':utc(),'monotonic':time.monotonic()}
|
||||
print('8 synthetic jobs accepted; waiting for burn alert', flush=True)
|
||||
seen=set()
|
||||
deadline=time.monotonic()+100
|
||||
while time.monotonic()<deadline:
|
||||
s=sample('worker_stopped'); samples.append(s)
|
||||
seen.update(s['all_firing'])
|
||||
if {'MessengerReadyBurnFast','MessengerQueueLag'} <= seen: break
|
||||
time.sleep(5)
|
||||
else: raise RuntimeError('Both ready fast burn and QueueLag were not observed in 100 seconds')
|
||||
docker('up','-d','--no-deps','worker'); worker_stopped=False
|
||||
out['worker_started']={'time':utc(),'monotonic':time.monotonic()}
|
||||
for att in accepted: client.wait_ready(actor,att,wait_seconds=90)
|
||||
out['all_ready']={'time':utc(),'monotonic':time.monotonic()}
|
||||
print('all jobs ready; waiting for alert to clear', flush=True)
|
||||
deadline=time.monotonic()+100
|
||||
while time.monotonic()<deadline:
|
||||
s=sample('recovery');samples.append(s)
|
||||
if not s['firing'] and 'MessengerQueueLag' not in s['all_firing']: break
|
||||
time.sleep(5)
|
||||
else: raise RuntimeError('Ready burn alert did not clear in 100 seconds')
|
||||
out['result']='PASS'
|
||||
finally:
|
||||
if worker_stopped:
|
||||
try: docker('up','-d','--no-deps','worker')
|
||||
except Exception: out['worker_restore_failed']=True
|
||||
(ROOT/'evidence/slo-ready-incident.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS: ready SLO incident; evidence/slo-ready-incident.json',flush=True)
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,31 @@
|
||||
rule_files:
|
||||
- /workspace/infra/prometheus/alerts.yaml
|
||||
evaluation_interval: 5s
|
||||
tests:
|
||||
- interval: 5s
|
||||
input_series: []
|
||||
alert_rule_test:
|
||||
- eval_time: 30s
|
||||
alertname: MessengerQueueTelemetryStale
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: 'Queue and ready SLO telemetry is stale'
|
||||
runbook: 'See docs/slo-runbook.md; check outbox and DB before interpreting ready SLO.'
|
||||
- interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_queue_sample_time_seconds{service_name="messenger-outbox"}'
|
||||
values: '0+5x20'
|
||||
- series: 'messenger_slo_unknown{service_name="messenger-outbox"}'
|
||||
values: '1x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 30s
|
||||
alertname: MessengerQueueTelemetryStale
|
||||
exp_alerts: []
|
||||
- eval_time: 30s
|
||||
alertname: MessengerReadyTimestampUnknown
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: 'Ready SLO commit timestamps unavailable'
|
||||
runbook: 'Check track_commit_timestamp and outbox; unknown events are not proof of SLO compliance.'
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Offline checks for trace propagation and telemetry redaction."""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from opentelemetry import trace, metrics
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
from src import telemetry as tel
|
||||
from src import broker
|
||||
|
||||
class TelemetryTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.exporter = InMemorySpanExporter()
|
||||
provider = TracerProvider()
|
||||
provider.add_span_processor(SimpleSpanProcessor(cls.exporter))
|
||||
trace.set_tracer_provider(provider)
|
||||
cls.reader = InMemoryMetricReader()
|
||||
metrics.set_meter_provider(MeterProvider(metric_readers=[cls.reader]))
|
||||
|
||||
def test_upload_outbox_publish_consume_context(self):
|
||||
self.exporter.clear()
|
||||
recorded = {}
|
||||
def publish(payload, headers):
|
||||
recorded.update(headers)
|
||||
with tel.tracer.start_as_current_span('upload') as upload:
|
||||
saved = tel.carrier()
|
||||
self.assertIn('traceparent', saved)
|
||||
with patch.object(broker, '_publish', side_effect=publish):
|
||||
asyncio.run(broker.publish({'type': 'attachment.process.v1', 'attempt': 2}, json.loads(json.dumps(saved))))
|
||||
with tel.tracer.start_as_current_span('consume', context=tel.extract(recorded), kind=tel.SpanKind.CONSUMER):
|
||||
pass
|
||||
spans = {s.name: s for s in self.exporter.get_finished_spans()}
|
||||
self.assertEqual(spans['attachment.publish'].parent.span_id, spans['upload'].context.span_id)
|
||||
self.assertEqual(spans['attachment.publish'].attributes['messaging.retry.attempt'], 2)
|
||||
self.assertEqual(spans['consume'].parent.span_id, spans['attachment.publish'].context.span_id)
|
||||
self.assertEqual(spans['consume'].context.trace_id, spans['upload'].context.trace_id)
|
||||
self.assertNotIn('type', recorded)
|
||||
|
||||
def test_log_formatter_only_explicit_fields(self):
|
||||
rec = logging.LogRecord('test', logging.INFO, __file__, 1, 'http.request', (), None)
|
||||
rec.authorization = 'secret'; rec.body = 'private message'; rec.route = '/api/v1/chats/{chat_id}'
|
||||
output = tel.JsonFormatter().format(rec)
|
||||
self.assertNotIn('secret', output)
|
||||
self.assertNotIn('private message', output)
|
||||
self.assertEqual(json.loads(output)['route'], '/api/v1/chats/{chat_id}')
|
||||
|
||||
def test_metrics_keep_route_template(self):
|
||||
attrs = {'method': 'POST', 'route': '/api/v1/chats/{chat_id}/attachments', 'status_class': '2xx'}
|
||||
tel.http_requests.add(1, attrs)
|
||||
tel.http_duration.record(0.125, attrs)
|
||||
result = self.reader.get_metrics_data()
|
||||
data = [item for resource in result.resource_metrics for scope in resource.scope_metrics for item in scope.metrics]
|
||||
requests = next(item for item in data if item.name == 'messenger.http.requests')
|
||||
point = next(point for point in requests.data.data_points if point.attributes == attrs)
|
||||
self.assertEqual(point.value, 1)
|
||||
self.assertEqual(set(point.attributes), {'method', 'route', 'status_class'})
|
||||
|
||||
def test_otlp_log_drops_secrets_and_exception(self):
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import InMemoryLogExporter, SimpleLogRecordProcessor
|
||||
exporter = InMemoryLogExporter()
|
||||
provider = LoggerProvider()
|
||||
provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))
|
||||
handler = LoggingHandler(logger_provider=provider)
|
||||
tel.log.addHandler(handler)
|
||||
try:
|
||||
with tel.tracer.start_as_current_span('log-test') as span:
|
||||
try:
|
||||
raise ValueError('secret exception body')
|
||||
except ValueError:
|
||||
tel.log.exception('http.request', extra={'authorization': 'secret token', 'body': 'private', 'route': '/api/v1/users'})
|
||||
record = exporter.get_finished_logs()[0].log_record
|
||||
self.assertEqual(record.body, 'http.request')
|
||||
self.assertEqual(record.trace_id, span.get_span_context().trace_id)
|
||||
self.assertNotIn('authorization', record.attributes)
|
||||
self.assertNotIn('body', record.attributes)
|
||||
self.assertFalse(any(k.startswith('exception.') for k in record.attributes))
|
||||
finally:
|
||||
tel.log.removeHandler(handler)
|
||||
provider.shutdown()
|
||||
|
||||
def test_failed_publish_marks_span_without_exception_content(self):
|
||||
self.exporter.clear()
|
||||
with patch.object(broker, '_publish', side_effect=OSError('private broker URL')):
|
||||
with self.assertRaises(broker.ApiError):
|
||||
asyncio.run(broker.publish({'attempt': 1}))
|
||||
span, = self.exporter.get_finished_spans()
|
||||
self.assertEqual(span.status.status_code, tel.StatusCode.ERROR)
|
||||
self.assertEqual(span.events, ())
|
||||
|
||||
def test_custom_http_methods_have_bounded_label(self):
|
||||
self.assertEqual(tel.http_method('POST'), 'POST')
|
||||
for value in ('CUSTOM1', 'CUSTOM2', 'secret'):
|
||||
self.assertEqual(tel.http_method(value), '_OTHER')
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Bounded Tempo failure with before/after counters and sampled Collector memory."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('capture',ROOT/'student-tests/capture_observability.py')
|
||||
capture=importlib.util.module_from_spec(spec);spec.loader.exec_module(capture)
|
||||
QUERIES={name:f'sum({name}{{exporter="otlp/tempo"}}) or vector(0)' for name in (
|
||||
'otelcol_exporter_enqueue_failed_spans_total','otelcol_exporter_send_failed_spans_total',
|
||||
'otelcol_exporter_sent_spans_total','otelcol_exporter_queue_size','otelcol_exporter_queue_capacity')}
|
||||
def docker(*args):
|
||||
return subprocess.run(['docker','compose',*args],cwd=ROOT,check=True,capture_output=True,text=True).stdout
|
||||
|
||||
def sample(phase):
|
||||
row={'phase':phase,'utc':datetime.now(timezone.utc).isoformat(),'monotonic':time.monotonic(),'metrics':{}}
|
||||
for name,query in QUERIES.items():
|
||||
result=capture.get('prometheus','api/v1/query',{'query':query})['data']['result']
|
||||
row['metrics'][name]=float(result[0]['value'][1])
|
||||
container=docker('ps','-q','otel-collector').strip()
|
||||
row['container_id']=container
|
||||
row['memory']=subprocess.run(['docker','stats','--no-stream','--format','{{.MemUsage}}',container],check=True,capture_output=True,text=True).stdout.strip()
|
||||
return row
|
||||
|
||||
def main():
|
||||
out={'queries':QUERIES,'samples':[]};stopped=False;load=None
|
||||
try:
|
||||
out['samples'].append(sample('before'))
|
||||
docker('stop','tempo');stopped=True
|
||||
subprocess.run(['make','test'],cwd=ROOT,check=True)
|
||||
load=subprocess.Popen([sys.executable,'tests/load.py','--duration','75','--concurrency','4','--output','evidence/review-tempo-load.json'],cwd=ROOT,stdout=subprocess.DEVNULL)
|
||||
while load.poll() is None:
|
||||
out['samples'].append(sample('outage'))
|
||||
time.sleep(10)
|
||||
if load.returncode: raise RuntimeError('load process failed')
|
||||
out['samples'].append(sample('before_restore'))
|
||||
docker('up','-d','--no-deps','tempo');stopped=False
|
||||
deadline=time.monotonic()+90
|
||||
while time.monotonic()<deadline:
|
||||
time.sleep(5)
|
||||
out['samples'].append(sample('recovery'))
|
||||
if out['samples'][-1]['metrics']['otelcol_exporter_queue_size']<=1: break
|
||||
else: raise RuntimeError('Tempo export queue did not drain within 90 seconds')
|
||||
first,last=out['samples'][0],out['samples'][-1]
|
||||
assert first['container_id']==last['container_id'],'Collector was recreated; deltas invalid'
|
||||
out['counter_deltas']={key:last['metrics'][key]-first['metrics'][key] for key in QUERIES if key.endswith('_total')}
|
||||
assert all(value>=0 for value in out['counter_deltas'].values()),'counter reset'
|
||||
out['load']=json.loads((ROOT/'evidence/review-tempo-load.json').read_text())
|
||||
assert out['load']['failed_requests']==0,out['load']
|
||||
out['result']='PASS'
|
||||
finally:
|
||||
if load is not None and load.poll() is None:
|
||||
load.terminate();load.wait(timeout=15)
|
||||
if stopped: docker('up','-d','--no-deps','tempo')
|
||||
(ROOT/'evidence/review-tempo-outage.json').write_text(json.dumps(out,indent=2)+'\n')
|
||||
print('PASS: Tempo outage; baseline/deltas/memory in evidence/review-tempo-outage.json')
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Synthetic upload with a known W3C trace ID; wait through a worker restart."""
|
||||
import secrets
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
|
||||
client = Client()
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
trace_id = secrets.token_hex(16)
|
||||
parent_id = secrets.token_hex(8)
|
||||
content = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 202,
|
||||
actor=actor, raw=content, headers={'Content-Type':'image/png',
|
||||
'traceparent':f'00-{trace_id}-{parent_id}-01'}, schema='Attachment')['json']
|
||||
print('trace_id:', trace_id, 'attachment_id:', attachment['id'], flush=True)
|
||||
started = time.monotonic()
|
||||
result = client.wait_ready(actor, attachment, wait_seconds=150)
|
||||
print('status:', result['status'], 'elapsed_seconds:', round(time.monotonic()-started, 3), flush=True)
|
||||
|
||||
(Path(__file__).resolve().parents[1] / 'evidence/review-retry-job.json').write_text(json.dumps({
|
||||
'utc': datetime.now(timezone.utc).isoformat(), 'trace_id': trace_id,
|
||||
'attachment_id': attachment['id'], 'status': result['status'],
|
||||
'elapsed_seconds': round(time.monotonic()-started, 3)}, indent=2)+'\n')
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Ten concurrent bounded uploads, with API-container peak memory sampling."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import http.client
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import quote
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def api_memory() -> dict[str, int]:
|
||||
ids = subprocess.check_output(["docker", "compose", "ps", "-q", "api-a", "api-b"], cwd=ROOT, text=True).split()
|
||||
return {container[:12]: int(subprocess.check_output(
|
||||
["docker", "exec", container, "cat", "/sys/fs/cgroup/memory.current"], text=True))
|
||||
for container in ids}
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument("--output", default="evidence/upload-memory.json")
|
||||
parser.add_argument("--size-mib", type=int, default=5)
|
||||
args = arguments(__doc__, configure)
|
||||
check(1 <= args.size_mib <= 10, "--size-mib must be 1..10")
|
||||
client = Client(args.base_url, args.ca_file, timeout=60)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
seed = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
payload = seed + b"\0" * (args.size_mib * 1024 * 1024 - len(seed))
|
||||
baseline, peak, samples, stop = api_memory(), {}, [], threading.Event()
|
||||
check(len(baseline) == 2, "memory experiment requires two running APIs")
|
||||
sampling_errors = []
|
||||
timestamps = []
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def sampler():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
values = api_memory()
|
||||
check(set(values) == set(baseline), "API containers changed during measurement")
|
||||
except Exception as error:
|
||||
sampling_errors.append(type(error).__name__)
|
||||
return
|
||||
timestamps.append(time.monotonic())
|
||||
samples.append(values)
|
||||
for name, value in values.items():
|
||||
peak[name] = max(peak.get(name, 0), value)
|
||||
time.sleep(.1)
|
||||
|
||||
def upload(index):
|
||||
barrier.wait(timeout=15)
|
||||
parsed = urlsplit(client.base)
|
||||
connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=60)
|
||||
|
||||
def chunks():
|
||||
for offset in range(0, len(payload), 512 * 1024):
|
||||
yield payload[offset:offset + 512 * 1024]
|
||||
# Keep all ten client streams open long enough for multiple memory samples.
|
||||
time.sleep(.5)
|
||||
|
||||
connection.request("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(f"load-{index}.png"),
|
||||
body=chunks(), encode_chunked=True,
|
||||
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"})
|
||||
response = connection.getresponse()
|
||||
body = response.read()
|
||||
connection.close()
|
||||
check(response.status == 201, "upload %s returned %s: %s" % (index, response.status, body[:200]))
|
||||
return json.loads(body)
|
||||
|
||||
started = time.monotonic()
|
||||
thread = threading.Thread(target=sampler, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
attachments = list(pool.map(upload, range(10)))
|
||||
finally:
|
||||
stop.set()
|
||||
thread.join(timeout=5)
|
||||
elapsed = time.monotonic() - started
|
||||
check(len({item["id"] for item in attachments}) == 10, "uploads were not distinct")
|
||||
check(not sampling_errors and len(samples) >= 2 and not thread.is_alive(),
|
||||
"memory sampler failed or did not collect enough samples: " + repr(sampling_errors))
|
||||
report = {
|
||||
"uploads": 10, "file_bytes": len(payload), "concurrency": 10,
|
||||
"api_upload_concurrency_limit": 1, "elapsed_seconds": round(elapsed, 3),
|
||||
"baseline_memory_bytes": baseline, "peak_memory_bytes": peak,
|
||||
"peak_growth_bytes": {name: peak.get(name, 0) - baseline.get(name, 0) for name in baseline},
|
||||
"samples": len(samples),
|
||||
"sample_intervals_seconds": [round(b-a, 3) for a, b in zip(timestamps, timestamps[1:])],
|
||||
"method": "cgroup memory.current via Docker; 0.1s pause AFTER each poll, actual intervals include Docker latency; ten clients start at a barrier and send chunked 512 KiB blocks every 0.5s. Peak is sampled, not continuous.",
|
||||
}
|
||||
destination = ROOT / args.output
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
check(all(value <= 512 * 1024 * 1024 for value in peak.values()), "API exceeded configured memory limit")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user