okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
64a91dcdc
main
1"""Read-only activity CLI contract, including retention gaps and portable parity.""" 2 3import io 4import json 5import os 6import subprocess 7import sys 8import tempfile 9import threading 10import unittest 11from contextlib import redirect_stdout 12from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 13from pathlib import Path 14from unittest import mock 15 16from strata_cli .cli import main 17from strata_cli .client import sanitize_telemetry 18from strata_cli .logs import ActivityContinuity ,activity_delta 19 20 21ROOT = Path (__file__ ).resolve ().parents [2 ] 22 23 24def sample (instance ,last ,seqs ): 25raw = {"schema_version" :1 ,"instance" : {"id" :instance ,"state" :"ready" }, 26"activity" : {"last_seq" :last ,"events" : [ 27 {"seq" :seq ,"at" :1_790_000_000.0 ,"request_id" :f" { seq :012x } " , 28"event" :"queued" ,"prompt" :"private" }for seq in seqs ]}} 29return sanitize_telemetry (raw ) 30 31 32class LogsTests (unittest .TestCase ): 33def test_monitor_continuity_reports_only_observed_gaps_and_resets_on_restart (self ): 34tracker = ActivityContinuity () 35tracker .add (sample ("instance-a" ,35 , [33 ,34 ,35 ])) 36self .assertEqual (tracker .status (), {"gap" :None ,"restarted" :False ,"regressed" :False }) 37tracker .add (sample ("instance-a" ,38 , [34 ,37 ,38 ])) 38self .assertEqual (tracker .status ()["gap" ], {"from_seq" :36 ,"to_seq" :36 }) 39tracker .add (sample ("instance-a" ,39 , [38 ,39 ])) 40self .assertEqual (tracker .status ()["gap" ], {"from_seq" :36 ,"to_seq" :36 }) 41tracker .add (sample ("instance-b" ,2 , [1 ,2 ])) 42self .assertEqual (tracker .status (), {"gap" :None ,"restarted" :True ,"regressed" :False }) 43tracker .add (sample ("instance-b" ,40 , [38 ,39 ,40 ])) 44self .assertEqual (tracker .status ()["gap" ], {"from_seq" :3 ,"to_seq" :37 }) 45tracker .add (sample ("instance-b" ,39 , [38 ,39 ])) 46self .assertTrue (tracker .status ()["regressed" ]) 47 48def test_quiet_logs_keep_activity_rows_and_json (self ): 49endpoint = mock .Mock () 50endpoint .snapshot .return_value = sample ("quiet-instance" ,1 , [1 ]) 51output = io .StringIO () 52with mock .patch ("strata_cli.monitor_commands.Endpoint" ,return_value = endpoint ), \ 53redirect_stdout (output ): 54self .assertEqual (main (["logs" ,"--quiet" ]),0 ) 55self .assertNotIn ("Recent request activity" ,output .getvalue ()) 56self .assertIn ("queued" ,output .getvalue ()) 57output = io .StringIO () 58with mock .patch ("strata_cli.monitor_commands.Endpoint" ,return_value = endpoint ), \ 59redirect_stdout (output ): 60self .assertEqual (main (["logs" ,"--quiet" ,"--json" ]),0 ) 61self .assertEqual (json .loads (output .getvalue ())["events" ][0 ]["event" ],"queued" ) 62 63def test_delta_reports_missing_sequences_and_restart_without_duplicates (self ): 64first = sample ("instance-a" ,35 , [33 ,34 ,35 ]) 65rows ,instance ,cursor = activity_delta (first ,None ,None ) 66self .assertEqual ([(r ["type" ],r .get ("from_seq" ),r .get ("to_seq" ))for r in rows ], 67 [("gap" ,1 ,32 ), ("activity" ,None ,None ), 68 ("activity" ,None ,None ), ("activity" ,None ,None )]) 69self .assertEqual (activity_delta (first ,instance ,cursor )[0 ], []) 70rows ,instance ,cursor = activity_delta (sample ("instance-a" ,39 , [35 ,38 ,39 ]),instance ,cursor ) 71self .assertEqual ([(r ["type" ],r .get ("from_seq" ),r .get ("to_seq" ))for r in rows ], 72 [("gap" ,36 ,37 ), ("activity" ,None ,None ), ("activity" ,None ,None )]) 73rows ,instance ,cursor = activity_delta (sample ("instance-b" ,2 , [1 ,2 ]),instance ,cursor ) 74self .assertEqual ([r ["type" ]for r in rows ], ["instance_change" ,"activity" ,"activity" ]) 75self .assertEqual ((instance ,cursor ), ("instance-b" ,2 )) 76 77def test_follow_jsonl_deduplicates_and_reports_gaps (self ): 78snapshots = [sample ("a" ,2 , [1 ,2 ]),sample ("a" ,2 , [1 ,2 ]), 79sample ("a" ,5 , [2 ,4 ,5 ]),sample ("b" ,1 , [1 ])] 80endpoint = mock .Mock () 81endpoint .snapshot .side_effect = snapshots 82stdout = io .StringIO () 83with mock .patch ("strata_cli.monitor_commands.Endpoint" ,return_value = endpoint ), \ 84mock .patch ("strata_cli.logs.time.sleep" ,side_effect = [None ,None ,None ,KeyboardInterrupt ]), \ 85redirect_stdout (stdout ): 86self .assertEqual (main (["logs" ,"--follow" ,"--output" ,"jsonl" ]),0 ) 87records = [json .loads (line )for line in stdout .getvalue ().splitlines ()] 88self .assertEqual ([r ["type" ]for r in records ], 89 ["activity" ,"activity" ,"gap" ,"activity" ,"activity" ,"instance_change" ,"activity" ]) 90self .assertEqual ((records [2 ]["from_seq" ],records [2 ]["to_seq" ]), (3 ,3 )) 91self .assertTrue (all (r ["schema_version" ]== 1 for r in records )) 92self .assertNotIn ("private" ,stdout .getvalue ()) 93 94def test_unsupported_sources_modes_and_absent_activity (self ): 95for args ,expected in ((["logs" ,"--source" ,"harness" ,"--output" ,"json" ],5 ), 96 (["logs" ,"--follow" ,"--output" ,"json" ],2 ), 97 (["logs" ,"--follow" ,"--json" ],2 ), 98 (["logs" ,"--output" ,"jsonl" ],2 ), 99 (["logs" ,"--interval" ,"0.1" ,"--output" ,"json" ],2 )): 100with self .subTest (args = args ),redirect_stdout (io .StringIO ())as stream : 101self .assertEqual (main (args ),expected ) 102self .assertEqual (json .loads (stream .getvalue ())["error" ]["code" ],expected ) 103endpoint = mock .Mock () 104endpoint .snapshot .return_value = sanitize_telemetry ({"schema_version" :1 ,"instance" : {"id" :"old" }}) 105with mock .patch ("strata_cli.monitor_commands.Endpoint" ,return_value = endpoint ), \ 106redirect_stdout (io .StringIO ())as stream : 107self .assertEqual (main (["logs" ,"--output" ,"json" ]),5 ) 108self .assertIn ("unavailable" ,json .loads (stream .getvalue ())["error" ]["message" ]) 109 110def test_one_shot_source_and_portable_use_read_only_key (self ): 111requests = [] 112raw = {"schema_version" :1 ,"instance" : {"id" :"fixture" }, 113"activity" : {"last_seq" :1 ,"events" : [ 114 {"seq" :1 ,"at" :1_790_000_000 ,"request_id" :"000000000001" , 115"event" :"finished" ,"outcome" :"stop" ,"prompt" :"private" }]}} 116 117class Handler (BaseHTTPRequestHandler ): 118def do_GET (self ): 119requests .append ((self .path ,self .headers .get ("Authorization" ))) 120if self .headers .get ("Authorization" )!= "Bearer read-key" : 121self .send_error (403 ) 122return 123body = json .dumps (raw ).encode () 124self .send_response (200 ) 125self .send_header ("Content-Type" ,"application/json" ) 126self .send_header ("Content-Length" ,str (len (body ))) 127self .end_headers () 128self .wfile .write (body ) 129 130def log_message (self ,* _args ): 131pass 132 133server = ThreadingHTTPServer (("127.0.0.1" ,0 ),Handler ) 134worker = threading .Thread (target = server .serve_forever ,daemon = True ) 135worker .start () 136try : 137url = f"http://127.0.0.1: { server . server_port } " 138with tempfile .TemporaryDirectory ()as directory : 139bundle = Path (directory )/ "strata-monitor.pyz" 140subprocess .run ([sys .executable ,str (ROOT / "packaging/monitor_bundle.py" ),"build" ,str (bundle )], 141check = True ,capture_output = True ,text = True ) 142clean_env = {k :v for k ,v in os .environ .items ()if k not in ("PYTHONPATH" ,"PYTHONHOME" )} 143clean_env ["STRATA_TELEMETRY_KEY" ]= "read-key" 144with mock .patch .dict (os .environ , {"STRATA_TELEMETRY_KEY" :"read-key" }), \ 145redirect_stdout (io .StringIO ())as source : 146self .assertEqual (main (["logs" ,"--url" ,url ,"--credential-env" , 147"STRATA_TELEMETRY_KEY" ,"--json" ]),0 ) 148portable = subprocess .run ([sys .executable ,"-S" ,str (bundle ),"logs" ,"--url" ,url , 149"--credential-env" ,"STRATA_TELEMETRY_KEY" ,"--output" ,"json" ], 150cwd = directory ,env = clean_env ,check = True ,capture_output = True ,text = True ) 151self .assertEqual (json .loads (source .getvalue ()),json .loads (portable .stdout )) 152self .assertEqual (json .loads (portable .stdout )["events" ][0 ]["event" ],"finished" ) 153self .assertNotIn ("private" ,portable .stdout ) 154self .assertEqual (requests , [("/v1/telemetry" ,"Bearer read-key" )]* 2 ) 155finally : 156server .shutdown () 157server .server_close () 158worker .join (timeout = 2 )