utopia-ia/elffuss-claw public
Changesets · Branches · Tags · Compare
| Changeset | d9c1fae2b99eba0b4952b7dfa859025ecf1823e4f64c6198daaecf7e9314e11a |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-11 18:57 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 18:57 +02:00 |
| Parents | ccfc538d93aa |
2 files changed
modified tests/litertcache.mjs +76 −35
| @@ -1,45 +1,86 @@ | ||
| 1 | -// Valida cachedModelBlob de litert.js: descarga 1 vez, cachea en Cache Storage | |
| 2 | -// (persistente) y en la 2ª llamada devuelve el blob SIN red (offline). Usa un | |
| 3 | -// fixture .litertlm determinista (no baja los GB reales). | |
| 1 | +// cachedModelBlob de litert.js: el .litertlm se baja una vez y la segunda sale | |
| 2 | +// sin red, por los dos caminos que tiene. | |
| 3 | +// | |
| 4 | +// 1. El de siempre desde 9ad584a: el almacén de modelos (runtime/model-store.js, | |
| 5 | +// caché compartida del broker o la OPFS de este origen). Antes esta prueba | |
| 6 | +// solo miraba Cache Storage, que ya no es por donde pasa el modelo. | |
| 7 | +// 2. El respaldo, cuando no hay OPFS: Cache Storage ('elffuss-models-v1'). | |
| 8 | +// | |
| 9 | +// El fichero es de mentira (page.route) y el broker se da por caído: no sale | |
| 10 | +// nada a la red ni se baja ningún modelo de verdad. | |
| 11 | +// | |
| 12 | +// BASE=http://localhost:8742 node tests/litertcache.mjs | |
| 4 | 13 | import { chromium } from 'playwright'; |
| 5 | -import { writeFileSync, rmSync } from 'node:fs'; | |
| 6 | -import { fileURLToPath } from 'node:url'; | |
| 7 | -import { dirname, join } from 'node:path'; | |
| 8 | -const BASE = process.env.BASE || 'http://localhost:8788'; | |
| 14 | +const BASE = process.env.BASE || 'http://localhost:8742'; | |
| 9 | 15 | const SIZE = 120000; |
| 10 | -let fails = 0; const ok = (n,c,e='')=>{console.log((c?'✅':'❌')+' '+n+(e?' — '+e:''));if(!c)fails++}; | |
| 11 | -const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web'); | |
| 12 | -const FIXP = join(WEB, '__litert_fixture.litertlm'); | |
| 13 | -writeFileSync(FIXP, Buffer.from(Array.from({length:SIZE},(_,i)=>i%256))); | |
| 14 | -process.on('exit', ()=>{ try{rmSync(FIXP)}catch{} }); | |
| 15 | -const FIX = BASE + '/__litert_fixture.litertlm'; | |
| 16 | +let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; | |
| 17 | +const DATOS = Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 256)); | |
| 16 | 18 | |
| 17 | -const b = await chromium.launch({args:['--enable-unsafe-webgpu','--use-angle=metal']}); | |
| 18 | -const ctx = await b.newContext(); | |
| 19 | -const p = await ctx.newPage(); | |
| 20 | -await p.goto(BASE+'/', {waitUntil:'domcontentloaded'}); | |
| 21 | - | |
| 22 | -const call = (u) => p.evaluate(async (u) => { | |
| 19 | +const b = await chromium.launch(); | |
| 20 | +async function pagina({ sinOPFS = false } = {}) { | |
| 21 | + const ctx = await b.newContext(); | |
| 22 | + await ctx.addInitScript(sin => { | |
| 23 | + try { sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* */ } | |
| 24 | + // Un navegador sin OPFS (o donde falla): el almacén devuelve null y litert.js | |
| 25 | + // tiene que caer a Cache Storage. | |
| 26 | + if (sin) try { Object.defineProperty(StorageManager.prototype, 'getDirectory', { value: undefined, configurable: true }); } catch { /* */ } | |
| 27 | + }, sinOPFS); | |
| 28 | + const p = await ctx.newPage(); | |
| 29 | + const peticiones = []; | |
| 30 | + await p.route('**/__litert_fixture.litertlm', route => { | |
| 31 | + const rango = route.request().headers().range || ''; | |
| 32 | + peticiones.push(rango || 'entero'); | |
| 33 | + const m = /bytes=(\d+)-(\d*)/.exec(rango); | |
| 34 | + if (!m) return route.fulfill({ status: 200, body: DATOS, headers: { 'content-type': 'application/octet-stream', 'content-length': String(SIZE) } }); | |
| 35 | + const desde = +m[1], hasta = m[2] ? +m[2] : SIZE - 1; | |
| 36 | + return route.fulfill({ status: 206, body: DATOS.subarray(desde, hasta + 1), headers: { 'content-range': `bytes ${desde}-${hasta}/${SIZE}`, 'accept-ranges': 'bytes' } }); | |
| 37 | + }); | |
| 38 | + await p.goto(BASE + '/robots.txt'); // una página del mismo origen, sin arrancar la app | |
| 39 | + return { ctx, p, peticiones }; | |
| 40 | +} | |
| 41 | +const llama = (p, u) => p.evaluate(async u => { | |
| 23 | 42 | const m = await import('/js/providers/litert.js'); |
| 24 | 43 | const msgs = []; |
| 25 | - const r = await m.cachedModelBlob(u, s => msgs.push(s)); | |
| 44 | + const r = await m.cachedModelBlob(u, s => msgs.push(String(s))); | |
| 26 | 45 | const blob = r instanceof Blob ? r : null; |
| 27 | - return { isBlob: !!blob, size: blob ? blob.size : 0, firstMsg: msgs[0]||'', lastMsg: msgs.at(-1)||'', type: typeof r }; | |
| 46 | + let malos = -1; | |
| 47 | + if (blob) { const v = new Uint8Array(await blob.arrayBuffer()); malos = 0; for (let i = 0; i < v.length; i++) if (v[i] !== i % 256) malos++; } | |
| 48 | + return { esBlob: !!blob, size: blob ? blob.size : 0, malos, primero: msgs[0] || '', tipo: typeof r }; | |
| 28 | 49 | }, u); |
| 29 | 50 | |
| 30 | -// 1) primera vez: descarga + cachea, devuelve Blob del tamaño correcto | |
| 31 | -let r = await call(FIX); | |
| 32 | -ok('1ª vez → Blob del tamaño real (descarga + cachea)', r.isBlob && r.size === SIZE, `${r.type} size=${r.size} · ${r.lastMsg}`); | |
| 33 | - | |
| 34 | -// 2) está en Cache Storage | |
| 35 | -const cached = await p.evaluate(async (u) => { const c = await caches.open('elffuss-models-v1'); return !!(await c.match(u)); }, FIX); | |
| 36 | -ok('el modelo quedó en Cache Storage', cached); | |
| 51 | +// 1 · camino normal: el almacén de modelos (OPFS) | |
| 52 | +{ | |
| 53 | + const { ctx, p, peticiones } = await pagina(); | |
| 54 | + const FIX = BASE + '/__litert_fixture.litertlm'; | |
| 55 | + let r = await llama(p, FIX); | |
| 56 | + ok('OPFS · 1ª vez → el modelo entero (lo baja y lo guarda)', r.esBlob && r.size === SIZE && r.malos === 0, JSON.stringify(r)); | |
| 57 | + const enOPFS = await p.evaluate(async () => { | |
| 58 | + try { const d = await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-models'); for await (const [n] of d.entries()) if (n.endsWith('.done')) return true; } catch { /* */ } | |
| 59 | + return false; | |
| 60 | + }); | |
| 61 | + ok('OPFS · quedó guardado en el almacén de modelos (no en Cache Storage)', enOPFS && !(await p.evaluate(async () => (await caches.keys()).includes('elffuss-models-v1')))); | |
| 62 | + peticiones.length = 0; | |
| 63 | + await ctx.setOffline(true); | |
| 64 | + r = await llama(p, FIX); | |
| 65 | + await ctx.setOffline(false); | |
| 66 | + ok('OPFS · 2ª vez SIN RED → desde disco, sin una petición', r.esBlob && r.size === SIZE && r.malos === 0 && peticiones.length === 0 && /disco/.test(r.primero), `${JSON.stringify(r)} · ${peticiones.length} peticiones`); | |
| 67 | + await ctx.close(); | |
| 68 | +} | |
| 37 | 69 | |
| 38 | -// 3) OFFLINE: 2ª llamada devuelve el blob desde caché sin red | |
| 39 | -await ctx.setOffline(true); | |
| 40 | -r = await call(FIX); | |
| 41 | -ok('2ª vez OFFLINE → Blob desde caché (no re-descarga)', r.isBlob && r.size === SIZE && /cach[eé]/i.test(r.firstMsg), `${r.size} · ${r.firstMsg}`); | |
| 42 | -await ctx.setOffline(false); | |
| 70 | +// 2 · respaldo sin OPFS: Cache Storage | |
| 71 | +{ | |
| 72 | + const { ctx, p, peticiones } = await pagina({ sinOPFS: true }); | |
| 73 | + const FIX = BASE + '/__litert_fixture.litertlm'; | |
| 74 | + let r = await llama(p, FIX); | |
| 75 | + ok('sin OPFS · 1ª vez → el modelo entero, por Cache Storage', r.esBlob && r.size === SIZE && r.malos === 0, JSON.stringify(r)); | |
| 76 | + ok('sin OPFS · quedó en Cache Storage', await p.evaluate(async u => !!(await (await caches.open('elffuss-models-v1')).match(u)), FIX)); | |
| 77 | + peticiones.length = 0; | |
| 78 | + await ctx.setOffline(true); | |
| 79 | + r = await llama(p, FIX); | |
| 80 | + await ctx.setOffline(false); | |
| 81 | + ok('sin OPFS · 2ª vez SIN RED → desde la caché, sin una petición', r.esBlob && r.size === SIZE && peticiones.length === 0 && /cach[eé]/i.test(r.primero), `${JSON.stringify(r)} · ${peticiones.length} peticiones`); | |
| 82 | + await ctx.close(); | |
| 83 | +} | |
| 43 | 84 | |
| 44 | -console.log(fails?`\n❌ ${fails} FALLO(S)`:'\n✅ CACHÉ LiteRT (blob) OK — descarga 1 vez, sirve offline'); | |
| 45 | -await b.close(); process.exit(fails?1:0); | |
| 85 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ LiteRT OK — se baja una vez y sirve sin red, con OPFS y sin ella'); | |
| 86 | +await b.close(); process.exit(fails ? 1 : 0); |
modified tests/modelcache.mjs +94 −47
| @@ -1,58 +1,105 @@ | ||
| 1 | -// Verifica la caché de modelos por service worker: descarga una vez, se sirve | |
| 2 | -// desde Cache Storage (incluso OFFLINE) y soporta range requests. Usa un fixture | |
| 3 | -// .litertlm determinista (byte[i] = i%256) para no bajar los GB reales. | |
| 1 | +// Caché de modelos: se baja UNA vez a disco y después se sirve sin red. | |
| 2 | +// | |
| 3 | +// Era la prueba del service worker que guardaba los modelos en Cache Storage. | |
| 4 | +// Ese service worker es inerte desde 852216e (rompía la carga de ONNX) y los | |
| 5 | +// pesos se guardan ahora en el almacén de modelos (runtime/model-store.js): la | |
| 6 | +// caché compartida del broker y, si no está, la OPFS de este origen. Esto prueba | |
| 7 | +// ese camino con la OPFS: descarga una vez, sirve desde disco sin tocar la red, | |
| 8 | +// los bytes son los del original, se lee por rangos y no deja la marca de | |
| 9 | +// «completo» hasta que lo está. | |
| 10 | +// | |
| 11 | +// El fichero es de mentira (page.route, byte[i] = i % 251) y el broker se da por | |
| 12 | +// caído, así que no sale nada a la red. | |
| 13 | +// | |
| 14 | +// BASE=http://localhost:8742 node tests/modelcache.mjs | |
| 4 | 15 | import { chromium } from 'playwright'; |
| 5 | -import { writeFileSync, rmSync } from 'node:fs'; | |
| 6 | -import { fileURLToPath } from 'node:url'; | |
| 7 | -import { dirname, join } from 'node:path'; | |
| 8 | -const BASE = process.env.BASE || 'http://localhost:8788'; | |
| 9 | -const FIX = BASE + '/__test_fixture.litertlm'; | |
| 10 | -const SIZE = 100000; | |
| 16 | +const BASE = process.env.BASE || 'http://localhost:8742'; | |
| 17 | +const FIX = BASE + '/__modelcache_fixture.litertlm'; | |
| 18 | +const SIZE = 300000; | |
| 11 | 19 | let fails = 0; |
| 12 | 20 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 13 | 21 | |
| 14 | -// fixture determinista (byte[i]=i%256) en web/, autolimpiado al terminar | |
| 15 | -const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web'); | |
| 16 | -const FIXPATH = join(WEB, '__test_fixture.litertlm'); | |
| 17 | -writeFileSync(FIXPATH, Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 256))); | |
| 18 | -const cleanup = () => { try { rmSync(FIXPATH); } catch {} }; | |
| 19 | -process.on('exit', cleanup); | |
| 20 | - | |
| 21 | -const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', '--use-angle=metal'] }); | |
| 22 | +const DATOS = Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 251)); | |
| 23 | +const peticiones = []; | |
| 24 | +const b = await chromium.launch(); | |
| 22 | 25 | const ctx = await b.newContext(); |
| 23 | -await ctx.addInitScript(() => { try { localStorage.setItem('elffuss.model', 'rules'); } catch {} }); | |
| 26 | +await ctx.addInitScript(() => { | |
| 27 | + try { localStorage.setItem('elffuss.model', 'rules'); sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* */ } | |
| 28 | +}); | |
| 24 | 29 | const p = await ctx.newPage({ viewport: { width: 1200, height: 800 } }); |
| 25 | -await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); | |
| 26 | - | |
| 27 | -// esperar a que el SW controle la página | |
| 28 | -const controlled = await p.waitForFunction(() => navigator.serviceWorker && navigator.serviceWorker.controller != null, null, { timeout: 10000 }).then(() => true).catch(() => false); | |
| 29 | -ok('el service worker controla la página', controlled); | |
| 30 | - | |
| 31 | -const fetchInfo = (u, opts) => p.evaluate(async ({ u, opts }) => { | |
| 32 | - const r = await fetch(u, opts); | |
| 33 | - const buf = new Uint8Array(await r.arrayBuffer()); | |
| 34 | - return { status: r.status, len: buf.length, cr: r.headers.get('content-range'), first: [...buf.slice(0, 4)], sample: [...buf.slice(0, 12)] }; | |
| 35 | -}, { u, opts }); | |
| 36 | - | |
| 37 | -// 1) primera descarga (el SW baja el fichero completo y lo cachea) | |
| 38 | -const r1 = await fetchInfo(FIX); | |
| 39 | -ok('primera petición devuelve el fichero completo', r1.status === 200 && r1.len === SIZE, `status ${r1.status}, ${r1.len}B`); | |
| 40 | - | |
| 41 | -// 2) OFFLINE: si está cacheado, se sigue sirviendo sin red | |
| 30 | +await p.route('**/__modelcache_fixture.litertlm', route => { | |
| 31 | + const rango = route.request().headers().range || ''; | |
| 32 | + peticiones.push(rango || 'entero'); | |
| 33 | + const m = /bytes=(\d+)-(\d*)/.exec(rango); | |
| 34 | + if (!m) return route.fulfill({ status: 200, body: DATOS, headers: { 'content-type': 'application/octet-stream', 'accept-ranges': 'bytes' } }); | |
| 35 | + const desde = +m[1], hasta = m[2] ? +m[2] : SIZE - 1; | |
| 36 | + return route.fulfill({ status: 206, body: DATOS.subarray(desde, hasta + 1), | |
| 37 | + headers: { 'content-type': 'application/octet-stream', 'accept-ranges': 'bytes', 'content-range': `bytes ${desde}-${hasta}/${SIZE}` } }); | |
| 38 | +}); | |
| 39 | +await p.goto(BASE + '/robots.txt'); // una página del mismo origen, sin arrancar la app | |
| 40 | + | |
| 41 | +const baja = () => p.evaluate(async u => { | |
| 42 | + const m = await import('/js/runtime/model-store.js'); | |
| 43 | + const msgs = []; | |
| 44 | + const f = await m.getModelFile(u, s => msgs.push(typeof s === 'string' ? s : JSON.stringify(s))); | |
| 45 | + if (!f) return { nulo: true, msgs }; | |
| 46 | + const buf = new Uint8Array(await f.arrayBuffer()); | |
| 47 | + let malos = 0; for (let i = 0; i < buf.length; i++) if (buf[i] !== i % 251) malos++; | |
| 48 | + return { size: f.size, malos, primero: msgs[0] || '', ultimo: msgs.at(-1) || '' }; | |
| 49 | +}, FIX); | |
| 50 | + | |
| 51 | +// 1) primera vez: se baja y queda en disco, entero y marcado como completo | |
| 52 | +const r1 = await baja(); | |
| 53 | +ok('primera vez: devuelve el modelo entero', r1.size === SIZE && r1.malos === 0, JSON.stringify(r1)); | |
| 54 | +const enDisco = await p.evaluate(async () => { | |
| 55 | + const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-models'); | |
| 56 | + const out = []; | |
| 57 | + for await (const [n, h] of dir.entries()) out.push(n + ':' + (h.kind === 'file' ? (await h.getFile()).size : 'dir')); | |
| 58 | + return out; | |
| 59 | +}); | |
| 60 | +// (Claw guarda los modelos partidos en trozos: <clave>.p0, .p1… Este cabe en uno.) | |
| 61 | +ok('queda en la OPFS del origen, con su marca de completo', enDisco.some(x => /\.litertlm(\.p0)?:/.test(x) && x.endsWith(':' + SIZE)) && enDisco.some(x => /\.done:/.test(x)), JSON.stringify(enDisco)); | |
| 62 | +ok(' …y la descarga sí pasó por la red', peticiones.length > 0, JSON.stringify(peticiones)); | |
| 63 | + | |
| 64 | +// 2) segunda vez SIN RED: sale del disco y no hace ninguna petición | |
| 65 | +peticiones.length = 0; | |
| 42 | 66 | await ctx.setOffline(true); |
| 43 | -const r2 = await fetchInfo(FIX).catch(e => ({ status: 0, err: String(e) })); | |
| 44 | -ok('OFFLINE se sirve desde la caché (prueba de que quedó cacheado)', r2.status === 200 && r2.len === SIZE, `status ${r2.status}, ${r2.len}B`); | |
| 45 | - | |
| 46 | -// 3) range request servido desde el blob cacheado (bytes 10..19) | |
| 47 | -const r3 = await fetchInfo(FIX, { headers: { Range: 'bytes=10-19' } }); | |
| 48 | -const expected = Array.from({ length: 10 }, (_, i) => (10 + i) % 256); | |
| 49 | -ok('range request → 206 con los bytes correctos', r3.status === 206 && r3.len === 10 && JSON.stringify(r3.sample.slice(0, 10)) === JSON.stringify(expected), `status ${r3.status}, cr=${r3.cr}, bytes=${r3.sample}`); | |
| 67 | +const r2 = await baja(); | |
| 50 | 68 | await ctx.setOffline(false); |
| 69 | +ok('segunda vez sin red: sale del disco, con los mismos bytes', r2.size === SIZE && r2.malos === 0, JSON.stringify(r2)); | |
| 70 | +ok(' …sin una sola petición', peticiones.length === 0, JSON.stringify(peticiones)); | |
| 71 | +ok(' …y lo dice («desde disco, sin descargar»)', /desde disco/.test(r2.primero), r2.primero); | |
| 72 | + | |
| 73 | +// 3) lectura por rangos desde el disco (la usa el motor por trozos) | |
| 74 | +const trozo = await p.evaluate(async u => { | |
| 75 | + const m = await import('/js/runtime/model-store.js'); | |
| 76 | + const r = await m.openRanged(u); | |
| 77 | + return { size: r.size, bytes: [...new Uint8Array(await r.slice(1000, 8))] }; | |
| 78 | +}, FIX); | |
| 79 | +const esperado = Array.from({ length: 8 }, (_, i) => (1000 + i) % 251); | |
| 80 | +ok('lectura por rangos desde el disco: los bytes justos', trozo.size === SIZE && JSON.stringify(trozo.bytes) === JSON.stringify(esperado), JSON.stringify(trozo)); | |
| 81 | + | |
| 82 | +// 4) una descarga cortada no deja la marca de completo: no se sirve a medias | |
| 83 | +await p.evaluate(async () => (await import('/js/runtime/model-store.js')).clearAll()); | |
| 84 | +await p.unroute('**/__modelcache_fixture.litertlm'); | |
| 85 | +await p.route('**/__modelcache_fixture.litertlm', route => { | |
| 86 | + const rango = route.request().headers().range || ''; | |
| 87 | + if (/bytes=0-0$/.test(rango)) return route.fulfill({ status: 206, body: DATOS.subarray(0, 1), headers: { 'content-range': `bytes 0-0/${SIZE}`, 'accept-ranges': 'bytes' } }); | |
| 88 | + return route.abort('failed'); | |
| 89 | +}); | |
| 90 | +const r4 = await p.evaluate(async u => { | |
| 91 | + const m = await import('/js/runtime/model-store.js'); | |
| 92 | + let err = null; try { await m.getModelFile(u); } catch (e) { err = String(e.message || e); } | |
| 93 | + const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-models'); | |
| 94 | + const nombres = []; for await (const [n] of dir.entries()) nombres.push(n); | |
| 95 | + return { err, completo: nombres.some(n => n.endsWith('.done')) }; | |
| 96 | +}, FIX); | |
| 97 | +ok('una descarga cortada falla y NO queda marcada como completa', !!r4.err && !r4.completo, JSON.stringify(r4)); | |
| 98 | + | |
| 99 | +// 5) el uso de almacenamiento lo refleja | |
| 100 | +const est = await p.evaluate(() => navigator.storage.estimate().then(e => e.usage || 0).catch(() => 0)); | |
| 101 | +ok('storage.estimate refleja lo guardado', est > 0, est > 0 ? 'hay uso' : 'sin uso'); | |
| 51 | 102 | |
| 52 | -// 4) el estimate reporta uso (>0) tras cachear | |
| 53 | -const est = await p.evaluate(() => navigator.storage.estimate().then(e => ({ usage: e.usage, persisted: null })).catch(() => ({ usage: 0 }))); | |
| 54 | -ok('storage.estimate refleja el uso cacheado', est.usage > 0, `${(est.usage / 1024 / 1024).toFixed(1)} MB`); | |
| 55 | - | |
| 56 | -console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ DE MODELOS OK — descarga 1 vez, persiste y sirve offline + ranges'); | |
| 103 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ DE MODELOS OK — se baja una vez a disco, se sirve sin red y por rangos'); | |
| 57 | 104 | await b.close(); |
| 58 | 105 | process.exit(fails ? 1 : 0); |