Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/scripts/allen/memory/test_memory.py # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / scripts / allen / memory / test_memory.py` 334 lines ยท 15132 bytes Raw Blame History 1 """Live tests for allen_memory against cortex-visitors (127.0.0.1:18096). 2 3 Run (engineering token injected by atlas-vault, never printed; visitor token read with sudo): 4 atlas-vault run CORTEX_TOKEN -- nice -n 19 python3 -m unittest -v test_memory 5 The engineering Cortex (127.0.0.1:18080) is only read (GET search/get), never written. 6 """ 7 import json 8 import os 9 import secrets 10 import socket 11 import subprocess 12 import sys 13 import time 14 import unittest 15 import urllib.error 16 import urllib.parse 17 import urllib.request 18 19 HERE = os.path.dirname(os.path.abspath(__file__)) 20 sys.path.insert(0, HERE) 21 import allen_memory # noqa: E402 22 from allen_memory import Memory # noqa: E402 23 24 VIS = 'http://127.0.0.1:18096' 25 ENG = 'http://127.0.0.1:18080' 26 ENG_SPACES = ['atlas-memory', 'aien-lessons', 'aien-sources'] 27 28 29 def _visitor_token(): 30 r = subprocess.run(['sudo', '-n', 'sed', '-n', 's/^CORTEX_TOKEN=//p', '/etc/cortex-visitors/env'], 31 capture_output=True, text=True) 32 return r.stdout.strip() 33 34 35 VTOK = _visitor_token() 36 ETOK = os.environ.get('CORTEX_TOKEN', '') 37 _NOPROXY = urllib.request.build_opener(urllib.request.ProxyHandler({})) 38 39 40 def http(method, base, path, token, body=None): 41 req = urllib.request.Request(base + path, method=method, 42 data=None if body is None else json.dumps(body).encode(), 43 headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}) 44 try: 45 with _NOPROXY.open(req, timeout=5) as r: 46 return r.status, json.loads(r.read()) 47 except urllib.error.HTTPError as e: 48 return e.code, None 49 50 51 def search(base, token, q, space): 52 return http('GET', base, '/api/cortex/search?' + urllib.parse.urlencode( 53 {'q': q, 'space': space, 'limit': 50}), token) 54 55 56 def vid(): 57 return secrets.token_hex(32) 58 59 60 def db_rows_with(marker): 61 """Count rows in the visitors DB whose content still holds marker (read-only, as the owner).""" 62 r = subprocess.run(['sudo', '-n', '-u', 'cortex-visitors', '/usr/bin/sqlite3', '-readonly', 63 '/var/lib/cortex-visitors/cortex.db', 64 "SELECT count(*) FROM entities WHERE instr(content, '%s') > 0;" % marker], 65 capture_output=True, text=True) 66 assert r.returncode == 0, r.stderr 67 return int(r.stdout.strip()) 68 69 70 class Base(unittest.TestCase): 71 def setUp(self): 72 self.assertEqual(len(VTOK), 64, 'visitor token not readable') 73 self.m = Memory(VIS, VTOK) 74 self.assertTrue(self.m.enabled) 75 self.vids = [] 76 77 def new(self): 78 v = vid() 79 self.vids.append(v) 80 return v 81 82 def tearDown(self): 83 for v in self.vids: 84 self.m.forget(v) 85 86 87 class RoundTrip(Base): 88 def test_roundtrip_and_cross_visitor(self): 89 a, b = self.new(), self.new() 90 self.assertEqual(self.m.recall(a), []) 91 self.assertEqual(self.m.remember(a, ['Builds a ray tracer in Omega', 'Lives near Austin']), 2) 92 got = self.m.recall(a) 93 self.assertEqual(sorted(got), ['Builds a ray tracer in Omega', 'Lives near Austin']) 94 # B sees nothing of A; after B writes, neither sees the other's entries. 95 self.assertEqual(self.m.recall(b), []) 96 self.assertEqual(self.m.remember(b, ['Prefers Rust examples']), 1) 97 self.assertEqual(self.m.recall(b), ['Prefers Rust examples']) 98 self.assertNotIn('Prefers Rust examples', self.m.recall(a)) 99 self.assertEqual(len(self.m.recall(a)), 2) 100 101 def test_limit(self): 102 a = self.new() 103 self.m.remember(a, ['alpha %s' % secrets.token_hex(12) for _ in range(5)]) 104 self.assertEqual(len(self.m.recall(a, limit=3)), 3) 105 self.assertEqual(len(self.m.recall(a)), 5) 106 107 def test_client_side_filter_rejects_foreign_rows(self): 108 # A row placed in A's space without A's tag (as a buggy/hostile writer would) is not returned. 109 a, b = self.new(), self.new() 110 sp = 'v-' + a 111 for alias, meta in ((['vid:' + b], {'vid': b}), (['vid:' + a], {'vid': b}), ([], {'vid': a})): 112 s, _ = http('POST', VIS, '/api/cortex/write', VTOK, {'kind': 'entity', 'value': { 113 'space': sp, 'entityType': 'visitor_note', 'canonicalName': 'm-' + secrets.token_hex(16), 114 'content': 'foreign row', 'aliases': alias, 'metadata': meta}}) 115 self.assertEqual(s, 201) 116 s, r = http('POST', VIS, '/api/cortex/search', VTOK, {'q': '', 'space': sp, 'limit': 50}) 117 self.assertEqual(len(r['results']), 3) # control: the server returns them 118 self.assertEqual(self.m.recall(a), []) # the client drops all three 119 self.m.remember(a, ['own row']) 120 self.assertEqual(self.m.recall(a), ['own row']) 121 # cleanup of the foreign rows: same wipe-then-retract the module uses 122 for e in r['results']: 123 self.m._wipe(a, {'id': e['id'], 'name': e['canonicalName']}) 124 self.assertEqual(db_rows_with('foreign row'), 0) 125 126 127 class Forget(Base): 128 def test_forget_deletes_all_and_spares_others(self): 129 a, b = self.new(), self.new() 130 mark = 'zqforget' + secrets.token_hex(8) 131 self.assertEqual(self.m.remember(a, ['%s one' % mark, '%s two xyz' % mark, 'third thing']), 3) 132 self.m.remember(b, ['B keeps this']) 133 self.assertEqual(db_rows_with(mark), 2) # control: text is in the DB before forget 134 self.assertEqual(self.m.forget(a), 3) 135 self.assertEqual(self.m.recall(a), []) 136 s, r = http('POST', VIS, '/api/cortex/search', VTOK, {'q': '', 'space': 'v-' + a, 'limit': 50}) 137 self.assertEqual((s, r['results']), (200, [])) 138 s, r = search(VIS, VTOK, mark, 'v-' + a) 139 self.assertEqual((s, r['results']), (200, [])) 140 self.assertEqual(db_rows_with(mark), 0) # content overwritten, not only hidden 141 self.assertEqual(self.m.recall(b), ['B keeps this']) 142 self.assertEqual(self.m.forget(a), 0) # nothing left 143 # A can be remembered again after forget 144 self.m.remember(a, ['%s again' % mark]) 145 self.assertEqual(self.m.recall(a), ['%s again' % mark]) 146 147 148 class Dedupe(Base): 149 def test_near_identical_updates(self): 150 a = self.new() 151 self.m.remember(a, ['Works on a compiler for Omega in Texas']) 152 self.m.remember(a, ['works on a compiler for omega, in Texas.', 'Works on a compiler for Omega in Texas!']) 153 self.assertEqual(len(self.m.recall(a)), 1) 154 self.m.remember(a, ['Works on the compiler for Omega in Texas']) 155 got = self.m.recall(a) 156 self.assertEqual(got, ['Works on the compiler for Omega in Texas']) # updated, not piled up 157 # within one batch too 158 self.m.remember(a, ['Has two cats named Ada and Bob', 'has two cats named ada and bob']) 159 self.assertEqual(len(self.m.recall(a)), 2) 160 # negative control: different facts are both kept 161 self.m.remember(a, ['Plays chess on weekends']) 162 self.assertEqual(len(self.m.recall(a)), 3) 163 164 def test_text_is_trimmed_and_capped(self): 165 a = self.new() 166 self.m.remember(a, [' spaced \n\t out ', 'x' * 1000, '', ' ', 7, None]) 167 got = self.m.recall(a) 168 self.assertIn('spaced out', got) 169 self.assertIn('x' * allen_memory.MAX_CHARS, got) 170 self.assertEqual(len(got), 2) 171 172 173 class Cap(Base): 174 def test_cap_drops_oldest(self): 175 a = self.new() 176 facts = ['fact %02d %s' % (i, secrets.token_hex(12)) for i in range(45)] 177 for i in range(0, 40, 10): 178 self.m.remember(a, facts[i:i + 10]) 179 time.sleep(0.01) 180 got = self.m.recall(a, limit=40) 181 self.assertEqual(len(got), 40) # control: at the cap nothing is dropped 182 self.assertIn(facts[0], got) 183 self.m.remember(a, facts[40:45]) 184 got = self.m.recall(a, limit=40) 185 self.assertEqual(len(got), 40) 186 self.assertEqual(set(got), set(facts[5:45])) # the five oldest went 187 self.assertIn(got[0], facts[40:45]) # newest first 188 s, r = http('POST', VIS, '/api/cortex/search', VTOK, {'q': '', 'space': 'v-' + a, 'limit': 50}) 189 self.assertEqual(len(r['results']), 40) 190 191 192 class Rejects(unittest.TestCase): 193 def test_bad_vids(self): 194 m = Memory(VIS, VTOK) 195 good = vid() 196 bads = [good.upper(), good[:-1], good + '0', good[:-1] + 'g', ' ' + good[1:], good[:-1] + '\n', 197 None, 123, b'\x00' * 64, '../' + good[3:], ''] 198 for bad in bads: 199 self.assertEqual(m.recall(bad), []) 200 self.assertEqual(m.remember(bad, ['should not be stored']), 0) 201 self.assertEqual(m.forget(bad), 0) 202 for bad in (good.upper(), good[:-1], good[:-1] + 'g'): 203 s, r = http('POST', VIS, '/api/cortex/search', VTOK, {'q': '', 'space': 'v-' + bad, 'limit': 50}) 204 self.assertEqual(r['results'], []) 205 def test_failures_never_raise(self): 206 v = vid() 207 for m in (Memory('http://127.0.0.1:9', VTOK), # nothing listening 208 Memory(VIS, 'wrong' * 13), # 401 209 Memory(VIS, ''), # disabled 210 Memory('http://10.1.2.3:18096', VTOK), # not loopback: disabled 211 Memory('https://127.0.0.1:18096', VTOK)): 212 t = time.monotonic() 213 self.assertEqual(m.recall(v), []) 214 self.assertEqual(m.remember(v, ['x']), 0) 215 self.assertEqual(m.forget(v), 0) 216 self.assertLess(time.monotonic() - t, 7) 217 self.assertFalse(Memory('http://10.1.2.3:18096', VTOK).enabled) 218 self.assertFalse(Memory(VIS, '').enabled) 219 # negative control: the same vid with the right token works 220 m = Memory(VIS, VTOK) 221 self.assertEqual(m.remember(v, ['ok']), 1) 222 self.assertEqual(m.recall(v), ['ok']) 223 self.assertEqual(m.forget(v), 1) 224 225 def test_timeout_is_two_seconds(self): 226 srv = socket.socket() 227 srv.bind(('127.0.0.1', 0)) 228 srv.listen(1) # accepts, never answers 229 m = Memory('http://127.0.0.1:%d' % srv.getsockname()[1], VTOK) 230 t = time.monotonic() 231 self.assertEqual(m.recall(vid()), []) 232 self.assertLess(time.monotonic() - t, 3.0) 233 srv.close() 234 235 236 @unittest.skipUnless(ETOK, 'run under atlas-vault run CORTEX_TOKEN') 237 class Isolation(Base): 238 def test_visitor_entry_never_in_engineering(self): 239 a = self.new() 240 mark = 'zqiso' + secrets.token_hex(10) 241 self.m.remember(a, ['marker %s here' % mark]) 242 s, r = search(VIS, VTOK, mark, 'v-' + a) # control: findable where it lives 243 self.assertEqual((s, len(r['results'])), (200, 1)) 244 for sp in ENG_SPACES + ['v-' + a]: 245 s, r = search(ENG, ETOK, mark, sp) 246 self.assertEqual(s, 200) 247 self.assertEqual(r['results'], [], sp) 248 s, r = http('POST', ENG, '/api/cortex/recall', ETOK, {'query': mark, 'space': 'v-' + a, 'limit': 5}) 249 self.assertEqual(s, 200) 250 self.assertFalse([x for x in r.get('results', []) if mark in json.dumps(x)]) 251 252 def test_tokens_do_not_cross(self): 253 s, r = search(ENG, ETOK, 'GB10', 'aien-lessons') 254 self.assertEqual(s, 200) # control: engineering path works 255 self.assertGreater(len(r['results']), 0) 256 eng_ids = [e['id'] for e in r['results']] 257 self.assertEqual(search(ENG, VTOK, 'GB10', 'aien-lessons')[0], 401) # visitor token refused 258 self.assertEqual(http('GET', ENG, '/api/cortex/get?' + urllib.parse.urlencode( 259 {'id': eng_ids[0], 'space': 'aien-lessons'}), VTOK)[0], 401) 260 self.assertEqual(search(VIS, ETOK, 'GB10', 'aien-lessons')[0], 401) # and the reverse 261 self.assertNotEqual(VTOK, ETOK) 262 263 def test_engineering_data_absent_from_visitors(self): 264 s, r = search(ENG, ETOK, 'GB10', 'aien-lessons') 265 self.assertGreater(len(r['results']), 0) 266 e = r['results'][0] 267 for sp in ENG_SPACES: 268 for q in ('GB10', e['canonicalName'].split()[-1]): 269 s2, r2 = search(VIS, VTOK, q, sp) 270 self.assertEqual((s2, r2['results']), (200, []), (sp, q)) 271 s2, r2 = http('POST', VIS, '/api/cortex/search', VTOK, {'q': '', 'space': sp, 'limit': 50}) 272 self.assertEqual(r2['results'], [], sp) 273 self.assertEqual(http('GET', VIS, '/api/cortex/get?' + urllib.parse.urlencode( 274 {'id': e['id'], 'space': 'aien-lessons'}), VTOK)[0], 404) 275 276 277 PROBE = r''' 278 import os, socket, sys 279 m = Memory.from_env() 280 v = sys.argv[1] if len(sys.argv) > 1 else os.environ['PROBE_VID'] 281 print('enabled', m.enabled) 282 print('recall', m.recall(v)) 283 def tcp(host, port): 284 s = socket.socket(); s.settimeout(2) 285 try: 286 s.connect((host, port)); return 'connected' 287 except OSError as e: 288 return 'errno %s %s' % (e.errno, type(e).__name__) 289 finally: 290 s.close() 291 print('loopback', tcp('127.0.0.1', 18096)) 292 print('other', tcp('127.0.0.53', 53)) 293 ''' 294 295 GATEWAY_PROPS = ['User=allen-chat', 'Group=allen-chat', 'SupplementaryGroups=allen-spool allen-drop', 296 'EnvironmentFile=-/etc/allen-chat/env', 'NoNewPrivileges=yes', 'CapabilityBoundingSet=', 297 'PrivateUsers=yes', 'ProtectSystem=strict', 'ProtectHome=yes', 'PrivateTmp=yes', 298 'RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK', 299 'IPAddressDeny=any', 'IPAddressAllow=127.0.0.1 100.64.0.2 100.64.0.3'] 300 301 302 def run_probe(props, v): 303 with open(os.path.join(HERE, 'allen_memory.py')) as f: 304 src = f.read() + PROBE 305 cmd = ['sudo', '-n', 'systemd-run', '--quiet', '--wait', '--pipe', '--collect', 306 '-E', 'PROBE_VID=' + v] 307 for p in props: 308 cmd += ['-p', p] 309 cmd += ['/usr/bin/python3', '-I', '-'] 310 r = subprocess.run(cmd, input=src, capture_output=True, text=True, timeout=60) 311 return r.returncode, r.stdout + r.stderr 312 313 314 class GatewayReach(Base): 315 def test_gateway_sandbox_reaches_visitors_store(self): 316 a = self.new() 317 self.m.remember(a, ['probe fact']) 318 rc, out = run_probe(GATEWAY_PROPS, a) 319 self.assertEqual(rc, 0, out) 320 self.assertIn('enabled True', out) # token present in /etc/allen-chat/env 321 self.assertIn("recall ['probe fact']", out) 322 self.assertIn('loopback connected', out) 323 self.assertIn('other errno', out) # IPAddressDeny drops the rest (timeout/EPERM) 324 # negative control: without IPAddressDeny/Allow the other address is reachable, 325 # so the failure above comes from the gateway's IP filter. 326 rc, out = run_probe([p for p in GATEWAY_PROPS if not p.startswith('IPAddress')], a) 327 self.assertIn('other connected', out) 328 # negative control: without the env file the store is disabled 329 rc, out = run_probe([p for p in GATEWAY_PROPS if not p.startswith('EnvironmentFile')], a) 330 self.assertIn('enabled False', out) 331 332 333 if __name__ == '__main__': 334 unittest.main(verbosity=2)