okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-189 (PR #189, the conversation snapshot core and RAM cache) into rel-0.1.30abbf12caf

main
5.7 KiB137 linesraw
1"""Destructive-to-cache HTTP smoke test for an EXCLUSIVE, idle Strata test server.
2
3Sends synthetic conversations, deliberately evicts cached conversations, and
4disconnects a streaming response. Never run while other clients are using it.
5Dry-run by default; --run explicitly enables network traffic. Does not restart
6or reconfigure the server. Use the private-engine parity gate for state hashes.
7"""
8import argparse
9import json
10from pathlib import Path
11import time
12import urllib.request
13import uuid
14
15
16def require(condition, message):
17    if not condition:
18        raise RuntimeError(message)
19
20
21class Client:
22    def __init__(self, url):
23        self.url = url.rstrip('/')
24
25    def metrics(self):
26        with urllib.request.urlopen(self.url + '/metrics', timeout=10) as response:
27            return json.load(response)
28
29    def request(self, model, content, stream=False, count=8):
30        body = {'model': model, 'messages': [{'role': 'user', 'content': content}],
31                'max_tokens': count, 'temperature': 0, 'stream': stream,
32                'chat_template_kwargs': {'enable_thinking': False}}
33        request = urllib.request.Request(self.url + '/v1/chat/completions',
34                                        data=json.dumps(body).encode(),
35                                        headers={'Content-Type': 'application/json'})
36        return urllib.request.urlopen(request, timeout=120)
37
38
39def run(client):
40    initial = client.metrics()
41    require(initial['live']['state'] == 'idle' and initial['live']['queued'] == 0, 'server is busy')
42    info = initial['engine']
43    slots = info.get('conversation_cache_slots', 0)
44    require(info.get('conversation_cache_mib', 0) > 0 and 1 <= slots <= 16,
45            'requires an enabled cache with 1–16 slots')
46    require(not info.get('api_key'), 'use an unauthenticated private test endpoint')
47    marker = 'cache-smoke-' + uuid.uuid4().hex
48    records = []
49
50    def before():
51        metrics = client.metrics()
52        require(metrics['live']['state'] == 'idle' and metrics['live']['queued'] == 0,
53                'concurrent client detected')
54        return max((r['time'] for r in metrics['requests']), default=0)
55
56    def after(stamp, label):
57        for _ in range(50):
58            metrics = client.metrics()
59            if metrics['live']['state'] == 'idle':
60                break
61            time.sleep(.2)
62        require(metrics['live']['state'] == 'idle', 'request did not drain')
63        fresh = [r for r in metrics['requests'] if r['time'] > stamp]
64        require(len(fresh) == 1 and metrics['live']['queued'] == 0,
65                'missing request evidence or concurrent traffic')
66        record = {'name': label, **fresh[0]}
67        records.append(record)
68        return record
69
70    def prompt(label):
71        return marker + ' ' + label + '\n' + '\n'.join(
72            f'Record {i}: blue square, green triangle, red circle.' for i in range(128)
73        ) + '\nName one color. Answer with one word.'
74
75    def ask(label, content):
76        stamp = before()
77        with client.request(info['model'], content) as response:
78            result = json.load(response)
79        require(bool(result.get('choices')), 'missing completion')
80        record = after(stamp, label)
81        require(record['finish'] in ('length', 'stop'), 'request did not finish normally')
82        return result['choices'][0]['message'], record
83
84    a, _ = ask('A', prompt('A'))
85    ask('B', prompt('B'))
86    restored, record = ask('A-restored', prompt('A'))
87    require(record['reused'] > 0 and a == restored, 'A/B/A reuse or output mismatch')
88    for i in range(slots + 1):
89        ask(f'evict-{i}', prompt(f'evict-{i}'))
90    _, record = ask('A-evicted', prompt('A'))
91    require(record['reused'] == 0, 'old A survived slot eviction')
92
93    text = marker + ' cancel: ' + 'blue green red. ' * 256
94    text += '\nCount from 1 to 1000, one number per line. Do not summarize.'
95    stamp = before()
96    with client.request(info['model'], text, stream=True, count=4096) as response:
97        for line in response:
98            if not line.startswith(b'data: ') or line.strip() == b'data: [DONE]':
99                continue
100            choices = json.loads(line[6:]).get('choices', [])
101            if choices and choices[0].get('delta', {}).get('content'):
102                break
103        else:
104            raise RuntimeError('no streamed content to cancel')
105    record = after(stamp, 'cancelled')
106    require(record['finish'] in ('disconnect', 'cancel') and 0 < record['output_tokens'] < 4096,
107            'stream cancellation not observed')
108    ask('after-cancel-B', marker + ' Unrelated B: say hello.')
109    _, record = ask('cancelled-A-restored', text)
110    require(record['reused'] > 0, 'cancelled conversation was not restored')
111    return {'engine_info': info, 'records': records}
112
113
114def main():
115    parser = argparse.ArgumentParser(description=__doc__)
116    parser.add_argument('--url', default='http://127.0.0.1:11434')
117    parser.add_argument('--output', type=Path, required=True, help='new results file; existing paths refused')
118    parser.add_argument('--run', action='store_true')
119    args = parser.parse_args()
120    if not args.run:
121        print('Dry run: HTTP A/B/A, slot eviction, cancellation and recovery. No network traffic.')
122        return
123    # Refuse accidental overwrites before generating traffic.
124    with args.output.open('x', encoding='utf-8') as output:
125        try:
126            result = run(Client(args.url))
127        except Exception as error:
128            json.dump({'passed': False, 'error': str(error)}, output, indent=2)
129            output.write('\n')
130            raise
131        json.dump({'passed': True, **result}, output, indent=2)
132        output.write('\n')
133    print(f'PASS: HTTP reuse, slot eviction, cancellation/recovery. Results: {args.output}')
134
135
136if __name__ == '__main__':
137    main()