utopia-ia/elffuss-code public
Changesets · Branches · Tags · Compare
| Changeset | edb5f99d205eaea3fb679a69b9b84ebea255e9441118e8c656c637abe2808c66 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-10-11 15:11 +02:00 |
| Parents | 3402fd88d963 |
4 files changed
modified tests/litertcache.mjs +75 −35
| @@ -1,46 +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 a2d33ec: 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:8799 node tests/litertcache.mjs | |
| 4 | 13 | import { chromium } from 'playwright'; |
| 5 | -import { CHROME_ARGS } from './chrome-args.mjs'; | |
| 6 | -import { writeFileSync, rmSync } from 'node:fs'; | |
| 7 | -import { fileURLToPath } from 'node:url'; | |
| 8 | -import { dirname, join } from 'node:path'; | |
| 9 | 14 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 10 | 15 | const SIZE = 120000; |
| 11 | -let fails = 0; const ok = (n,c,e='')=>{console.log((c?'✅':'❌')+' '+n+(e?' — '+e:''));if(!c)fails++}; | |
| 12 | -const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web'); | |
| 13 | -const FIXP = join(WEB, '__litert_fixture.litertlm'); | |
| 14 | -writeFileSync(FIXP, Buffer.from(Array.from({length:SIZE},(_,i)=>i%256))); | |
| 15 | -process.on('exit', ()=>{ try{rmSync(FIXP)}catch{} }); | |
| 16 | -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)); | |
| 17 | 18 | |
| 18 | -const b = await chromium.launch({args:['--enable-unsafe-webgpu',...CHROME_ARGS]}); | |
| 19 | -const ctx = await b.newContext(); | |
| 20 | -const p = await ctx.newPage(); | |
| 21 | -await p.goto(BASE+'/', {waitUntil:'domcontentloaded'}); | |
| 22 | - | |
| 23 | -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 + '/manifest.json'); | |
| 39 | + return { ctx, p, peticiones }; | |
| 40 | +} | |
| 41 | +const llama = (p, u) => p.evaluate(async u => { | |
| 24 | 42 | const m = await import('/js/providers/litert.js'); |
| 25 | 43 | const msgs = []; |
| 26 | - const r = await m.cachedModelBlob(u, s => msgs.push(s)); | |
| 44 | + const r = await m.cachedModelBlob(u, s => msgs.push(String(s))); | |
| 27 | 45 | const blob = r instanceof Blob ? r : null; |
| 28 | - 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 }; | |
| 29 | 49 | }, u); |
| 30 | 50 | |
| 31 | -// 1) primera vez: descarga + cachea, devuelve Blob del tamaño correcto | |
| 32 | -let r = await call(FIX); | |
| 33 | -ok('1ª vez → Blob del tamaño real (descarga + cachea)', r.isBlob && r.size === SIZE, `${r.type} size=${r.size} · ${r.lastMsg}`); | |
| 34 | - | |
| 35 | -// 2) está en Cache Storage | |
| 36 | -const cached = await p.evaluate(async (u) => { const c = await caches.open('elffuss-models-v1'); return !!(await c.match(u)); }, FIX); | |
| 37 | -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 | +} | |
| 38 | 69 | |
| 39 | -// 3) OFFLINE: 2ª llamada devuelve el blob desde caché sin red | |
| 40 | -await ctx.setOffline(true); | |
| 41 | -r = await call(FIX); | |
| 42 | -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}`); | |
| 43 | -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 | +} | |
| 44 | 84 | |
| 45 | -console.log(fails?`\n❌ ${fails} FALLO(S)`:'\n✅ CACHÉ LiteRT (blob) OK — descarga 1 vez, sirve offline'); | |
| 46 | -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 +93 −48
| @@ -1,59 +1,104 @@ | ||
| 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 75adafc (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:8799 node tests/modelcache.mjs | |
| 4 | 15 | import { chromium } from 'playwright'; |
| 5 | -import { CHROME_ARGS } from './chrome-args.mjs'; | |
| 6 | -import { writeFileSync, rmSync } from 'node:fs'; | |
| 7 | -import { fileURLToPath } from 'node:url'; | |
| 8 | -import { dirname, join } from 'node:path'; | |
| 9 | 16 | const BASE = process.env.BASE || 'http://localhost:8799'; |
| 10 | -const FIX = BASE + '/__test_fixture.litertlm'; | |
| 11 | -const SIZE = 100000; | |
| 17 | +const FIX = BASE + '/__modelcache_fixture.litertlm'; | |
| 18 | +const SIZE = 300000; | |
| 12 | 19 | let fails = 0; |
| 13 | 20 | const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 14 | 21 | |
| 15 | -// fixture determinista (byte[i]=i%256) en web/, autolimpiado al terminar | |
| 16 | -const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web'); | |
| 17 | -const FIXPATH = join(WEB, '__test_fixture.litertlm'); | |
| 18 | -writeFileSync(FIXPATH, Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 256))); | |
| 19 | -const cleanup = () => { try { rmSync(FIXPATH); } catch {} }; | |
| 20 | -process.on('exit', cleanup); | |
| 21 | - | |
| 22 | -const b = await chromium.launch({ args: ['--enable-unsafe-webgpu', ...CHROME_ARGS] }); | |
| 22 | +const DATOS = Buffer.from(Array.from({ length: SIZE }, (_, i) => i % 251)); | |
| 23 | +const peticiones = []; | |
| 24 | +const b = await chromium.launch(); | |
| 23 | 25 | const ctx = await b.newContext(); |
| 24 | -await ctx.addInitScript(() => { try { localStorage.setItem('elffusscode.model', 'rules'); } catch {} }); | |
| 26 | +await ctx.addInitScript(() => { | |
| 27 | + try { localStorage.setItem('elffusscode.model', 'rules'); sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* */ } | |
| 28 | +}); | |
| 25 | 29 | const p = await ctx.newPage({ viewport: { width: 1200, height: 800 } }); |
| 26 | -await p.goto(BASE + '/?test-opfs', { waitUntil: 'domcontentloaded' }); | |
| 27 | - | |
| 28 | -// esperar a que el SW controle la página | |
| 29 | -const controlled = await p.waitForFunction(() => navigator.serviceWorker && navigator.serviceWorker.controller != null, null, { timeout: 10000 }).then(() => true).catch(() => false); | |
| 30 | -ok('el service worker controla la página', controlled); | |
| 31 | - | |
| 32 | -const fetchInfo = (u, opts) => p.evaluate(async ({ u, opts }) => { | |
| 33 | - const r = await fetch(u, opts); | |
| 34 | - const buf = new Uint8Array(await r.arrayBuffer()); | |
| 35 | - return { status: r.status, len: buf.length, cr: r.headers.get('content-range'), first: [...buf.slice(0, 4)], sample: [...buf.slice(0, 12)] }; | |
| 36 | -}, { u, opts }); | |
| 37 | - | |
| 38 | -// 1) primera descarga (el SW baja el fichero completo y lo cachea) | |
| 39 | -const r1 = await fetchInfo(FIX); | |
| 40 | -ok('primera petición devuelve el fichero completo', r1.status === 200 && r1.len === SIZE, `status ${r1.status}, ${r1.len}B`); | |
| 41 | - | |
| 42 | -// 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 + '/manifest.json'); | |
| 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 | +ok('queda en la OPFS del origen, con su marca de completo', enDisco.some(x => x.endsWith('.litertlm:' + SIZE)) && enDisco.some(x => /\.done:/.test(x)), JSON.stringify(enDisco)); | |
| 61 | +ok(' …y la descarga sí pasó por la red', peticiones.length > 0, JSON.stringify(peticiones)); | |
| 62 | + | |
| 63 | +// 2) segunda vez SIN RED: sale del disco y no hace ninguna petición | |
| 64 | +peticiones.length = 0; | |
| 43 | 65 | await ctx.setOffline(true); |
| 44 | -const r2 = await fetchInfo(FIX).catch(e => ({ status: 0, err: String(e) })); | |
| 45 | -ok('OFFLINE se sirve desde la caché (prueba de que quedó cacheado)', r2.status === 200 && r2.len === SIZE, `status ${r2.status}, ${r2.len}B`); | |
| 46 | - | |
| 47 | -// 3) range request servido desde el blob cacheado (bytes 10..19) | |
| 48 | -const r3 = await fetchInfo(FIX, { headers: { Range: 'bytes=10-19' } }); | |
| 49 | -const expected = Array.from({ length: 10 }, (_, i) => (10 + i) % 256); | |
| 50 | -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}`); | |
| 66 | +const r2 = await baja(); | |
| 51 | 67 | await ctx.setOffline(false); |
| 52 | - | |
| 53 | -// 4) el estimate reporta uso (>0) tras cachear | |
| 54 | -const est = await p.evaluate(() => navigator.storage.estimate().then(e => ({ usage: e.usage, persisted: null })).catch(() => ({ usage: 0 }))); | |
| 55 | -ok('storage.estimate refleja el uso cacheado', est.usage > 0, `${(est.usage / 1024 / 1024).toFixed(1)} MB`); | |
| 56 | - | |
| 57 | -console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ CACHÉ DE MODELOS OK — descarga 1 vez, persiste y sirve offline + ranges'); | |
| 68 | +ok('segunda vez sin red: sale del disco, con los mismos bytes', r2.size === SIZE && r2.malos === 0, JSON.stringify(r2)); | |
| 69 | +ok(' …sin una sola petición', peticiones.length === 0, JSON.stringify(peticiones)); | |
| 70 | +ok(' …y lo dice («desde disco, sin descargar»)', /desde disco/.test(r2.primero), r2.primero); | |
| 71 | + | |
| 72 | +// 3) lectura por rangos desde el disco (la usa el motor por trozos) | |
| 73 | +const trozo = await p.evaluate(async u => { | |
| 74 | + const m = await import('/js/runtime/model-store.js'); | |
| 75 | + const r = await m.openRanged(u); | |
| 76 | + return { size: r.size, bytes: [...new Uint8Array(await r.slice(1000, 8))] }; | |
| 77 | +}, FIX); | |
| 78 | +const esperado = Array.from({ length: 8 }, (_, i) => (1000 + i) % 251); | |
| 79 | +ok('lectura por rangos desde el disco: los bytes justos', trozo.size === SIZE && JSON.stringify(trozo.bytes) === JSON.stringify(esperado), JSON.stringify(trozo)); | |
| 80 | + | |
| 81 | +// 4) una descarga cortada no deja la marca de completo: no se sirve a medias | |
| 82 | +await p.evaluate(async () => (await import('/js/runtime/model-store.js')).clearAll()); | |
| 83 | +await p.unroute('**/__modelcache_fixture.litertlm'); | |
| 84 | +await p.route('**/__modelcache_fixture.litertlm', route => { | |
| 85 | + const rango = route.request().headers().range || ''; | |
| 86 | + 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' } }); | |
| 87 | + return route.abort('failed'); | |
| 88 | +}); | |
| 89 | +const r4 = await p.evaluate(async u => { | |
| 90 | + const m = await import('/js/runtime/model-store.js'); | |
| 91 | + let err = null; try { await m.getModelFile(u); } catch (e) { err = String(e.message || e); } | |
| 92 | + const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle('elffuss-models'); | |
| 93 | + const nombres = []; for await (const [n] of dir.entries()) nombres.push(n); | |
| 94 | + return { err, completo: nombres.some(n => n.endsWith('.done')) }; | |
| 95 | +}, FIX); | |
| 96 | +ok('una descarga cortada falla y NO queda marcada como completa', !!r4.err && !r4.completo, JSON.stringify(r4)); | |
| 97 | + | |
| 98 | +// 5) el uso de almacenamiento lo refleja | |
| 99 | +const est = await p.evaluate(() => navigator.storage.estimate().then(e => e.usage || 0).catch(() => 0)); | |
| 100 | +ok('storage.estimate refleja lo guardado', est > 0, est > 0 ? 'hay uso' : 'sin uso'); | |
| 101 | + | |
| 102 | +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'); | |
| 58 | 103 | await b.close(); |
| 59 | 104 | process.exit(fails ? 1 : 0); |
modified tests/modelcache_honest.mjs +65 −49
| @@ -1,68 +1,84 @@ | ||
| 1 | -// Guardia: si NO se puede cachear el modelo, hay que DECIRLO. | |
| 1 | +// Guardia: si NO se puede guardar el modelo, hay que DECIRLO. | |
| 2 | 2 | // Bug real (ago-2026): cachedModelBlob prometía en el progreso «se cachea para |
| 3 | 3 | // la próxima vez», y si cache.put fallaba (ventana privada, disco lleno, cuota) |
| 4 | 4 | // se tragaba la excepción y devolvía la URL. El usuario se re-bajaba GIGABYTES |
| 5 | 5 | // cada sesión sin enterarse de por qué. Es la misma enfermedad que el resto de |
| 6 | 6 | // la ronda: fallo silencioso presentado como éxito. |
| 7 | -// Determinista: se fuerza el fallo de cache.put, no hace falta ni GPU ni GB. | |
| 7 | +// | |
| 8 | +// Desde a2d33ec el modelo se guarda primero en el almacén de modelos (OPFS) y | |
| 9 | +// Cache Storage es el respaldo: esta prueba fallaba sobre Cache Storage, que ya | |
| 10 | +// no es el camino normal. Ahora se fuerza el fallo donde se guarda de verdad: | |
| 11 | +// 1. normal: se guarda en disco y no se avisa de nada; | |
| 12 | +// 2. falla la OPFS (cuota): se dice, y el modelo sigue llegando por la caché; | |
| 13 | +// 3. fallan las dos: se dice con la causa probable, y la carga sigue (URL). | |
| 14 | +// Determinista: fichero de mentira (page.route) y broker dado por caído. | |
| 15 | +// | |
| 16 | +// BASE=http://localhost:8799 node tests/modelcache_honest.mjs | |
| 8 | 17 | import { chromium } from 'playwright'; |
| 9 | -import { writeFileSync, rmSync } from 'node:fs'; | |
| 10 | -import { fileURLToPath } from 'node:url'; | |
| 11 | -import { dirname, join } from 'node:path'; | |
| 12 | 18 | const BASE = process.env.BASE || 'http://localhost:8790'; |
| 13 | 19 | let fails = 0; const ok = (n, c, e = '') => { console.log((c ? '✅' : '❌') + ' ' + n + (e ? ' — ' + e : '')); if (!c) fails++; }; |
| 14 | - | |
| 15 | -const WEB = join(dirname(fileURLToPath(import.meta.url)), '..', 'web'); | |
| 16 | -const FIXP = join(WEB, '__honest_fixture.litertlm'); | |
| 17 | -writeFileSync(FIXP, Buffer.alloc(50000, 7)); | |
| 18 | -process.on('exit', () => { try { rmSync(FIXP); } catch {} }); | |
| 19 | -const FIX = BASE + '/__honest_fixture.litertlm'; | |
| 20 | +const SIZE = 50000; | |
| 21 | +const DATOS = Buffer.alloc(SIZE, 7); | |
| 20 | 22 | |
| 21 | 23 | const b = await chromium.launch(); |
| 22 | -const p = await (await b.newContext()).newPage(); | |
| 23 | -await p.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); | |
| 24 | +async function pagina({ opfsLlena = false, cacheLlena = false } = {}) { | |
| 25 | + const ctx = await b.newContext(); | |
| 26 | + await ctx.addInitScript(({ opfsLlena, cacheLlena }) => { | |
| 27 | + try { sessionStorage.setItem('elffuss.broker.down', '1'); } catch { /* */ } | |
| 28 | + const cuota = () => { const e = new Error('Quota exceeded'); e.name = 'QuotaExceededError'; return e; }; | |
| 29 | + // Disco lleno para la OPFS: abrir el fichero se puede, escribir bytes no. | |
| 30 | + if (opfsLlena) FileSystemWritableFileStream.prototype.write = async function () { throw cuota(); }; | |
| 31 | + if (cacheLlena) Cache.prototype.put = async function () { throw cuota(); }; | |
| 32 | + }, { opfsLlena, cacheLlena }); | |
| 33 | + const p = await ctx.newPage(); | |
| 34 | + await p.route('**/__honest_fixture.litertlm', route => { | |
| 35 | + const rango = route.request().headers().range || ''; | |
| 36 | + 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' } }); | |
| 37 | + return route.fulfill({ status: 200, body: DATOS, headers: { 'content-type': 'application/octet-stream', 'content-length': String(SIZE) } }); | |
| 38 | + }); | |
| 39 | + await p.goto(BASE + '/manifest.json'); | |
| 40 | + return { ctx, p }; | |
| 41 | +} | |
| 42 | +const carga = p => p.evaluate(async u => { | |
| 43 | + const m = await import('/js/providers/litert.js'); | |
| 44 | + const msgs = []; | |
| 45 | + let res, err = null; | |
| 46 | + try { res = await m.cachedModelBlob(u, s => msgs.push(String(s))); } catch (e) { err = e.message; } | |
| 47 | + return { | |
| 48 | + err, esBlob: res instanceof Blob, size: res instanceof Blob ? res.size : 0, esURL: typeof res === 'string', | |
| 49 | + aviso: msgs.find(s => /No se pudo guardar/.test(s)) || '', | |
| 50 | + explica: msgs.some(s => /No se pudo guardar/.test(s) && /privada|espacio/i.test(s)), | |
| 51 | + }; | |
| 52 | +}, BASE + '/__honest_fixture.litertlm'); | |
| 53 | + | |
| 54 | +// 1) normal: se guarda en disco y no avisa de ningún fallo | |
| 55 | +{ | |
| 56 | + const { ctx, p } = await pagina(); | |
| 57 | + const r = await carga(p); | |
| 58 | + ok('normal: devuelve el modelo guardado', r.esBlob && r.size === SIZE, JSON.stringify(r)); | |
| 59 | + ok('normal: no avisa de fallo cuando SÍ lo guarda', !r.aviso, r.aviso); | |
| 60 | + await ctx.close(); | |
| 61 | +} | |
| 24 | 62 | |
| 25 | -// 1) camino normal: cachea y devuelve Blob, sin avisos de fallo | |
| 63 | +// 2) la OPFS no puede guardarlo (cuota): lo dice, y sigue por Cache Storage | |
| 26 | 64 | { |
| 27 | - const r = await p.evaluate(async (u) => { | |
| 28 | - const m = await import('/js/providers/litert.js'); | |
| 29 | - const msgs = []; | |
| 30 | - const res = await m.cachedModelBlob(u, s => msgs.push(s)); | |
| 31 | - return { isBlob: res instanceof Blob, size: res instanceof Blob ? res.size : 0, warned: msgs.some(s => /No se pudo guardar/.test(s)) }; | |
| 32 | - }, FIX); | |
| 33 | - ok('normal: devuelve Blob cacheado', r.isBlob && r.size === 50000, `size=${r.size}`); | |
| 34 | - ok('normal: no avisa de fallo cuando SÍ cachea', !r.warned); | |
| 65 | + const { ctx, p } = await pagina({ opfsLlena: true }); | |
| 66 | + const r = await carga(p); | |
| 67 | + ok('disco lleno (OPFS): NO revienta la carga, el modelo llega por la caché', !r.err && r.esBlob && r.size === SIZE, r.err || JSON.stringify(r)); | |
| 68 | + ok('disco lleno (OPFS): lo DICE en el progreso (no silencioso)', /disco del navegador/.test(r.aviso), r.aviso.slice(0, 120)); | |
| 69 | + ok('disco lleno (OPFS): explica la causa probable', r.explica); | |
| 70 | + await ctx.close(); | |
| 35 | 71 | } |
| 36 | 72 | |
| 37 | -// 2) cache.put FALLA (cuota/ventana privada/disco): debe avisar y seguir usable | |
| 73 | +// 3) no se puede guardar en ningún sitio: lo dice y la carga sigue con la URL | |
| 38 | 74 | { |
| 39 | - const r = await p.evaluate(async (u) => { | |
| 40 | - const m = await import('/js/providers/litert.js'); | |
| 41 | - const real = caches.open.bind(caches); | |
| 42 | - caches.open = async (n) => { | |
| 43 | - const c = await real(n); | |
| 44 | - await c.delete(u); // que no lo sirva de caché previa | |
| 45 | - return new Proxy(c, { | |
| 46 | - get: (t, k) => k === 'put' | |
| 47 | - ? async () => { const e = new Error('Quota exceeded'); e.name = 'QuotaExceededError'; throw e; } | |
| 48 | - : (typeof t[k] === 'function' ? t[k].bind(t) : t[k]), | |
| 49 | - }); | |
| 50 | - }; | |
| 51 | - const msgs = []; | |
| 52 | - let res, err = null; | |
| 53 | - try { res = await m.cachedModelBlob(u, s => msgs.push(s)); } catch (e) { err = e.message; } | |
| 54 | - caches.open = real; | |
| 55 | - return { | |
| 56 | - err, devuelveURL: typeof res === 'string', | |
| 57 | - aviso: msgs.find(s => /No se pudo guardar/.test(s)) || '', | |
| 58 | - explica: msgs.some(s => /privada|espacio/i.test(s)), | |
| 59 | - }; | |
| 60 | - }, FIX); | |
| 61 | - ok('fallo al cachear: NO revienta la carga (devuelve la URL)', !r.err && r.devuelveURL, r.err || ''); | |
| 62 | - ok('fallo al cachear: lo DICE en el progreso (no silencioso)', !!r.aviso, r.aviso.slice(0, 110)); | |
| 63 | - ok('fallo al cachear: explica la causa probable', r.explica); | |
| 75 | + const { ctx, p } = await pagina({ opfsLlena: true, cacheLlena: true }); | |
| 76 | + const r = await carga(p); | |
| 77 | + ok('sin sitio donde guardarlo: NO revienta la carga (devuelve la URL)', !r.err && r.esURL, r.err || JSON.stringify(r)); | |
| 78 | + ok('sin sitio donde guardarlo: lo DICE, con la causa probable', !!r.aviso && r.explica, r.aviso.slice(0, 120)); | |
| 79 | + await ctx.close(); | |
| 64 | 80 | } |
| 65 | 81 | |
| 66 | -console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ caché de modelo HONESTA — si no cachea, lo dice'); | |
| 82 | +console.log(fails ? `\n❌ ${fails} FALLO(S)` : '\n✅ caché de modelo HONESTA — si no lo guarda, lo dice'); | |
| 67 | 83 | await b.close(); |
| 68 | 84 | process.exit(fails ? 1 : 0); |
modified web/js/providers/litert.js +11 −1
| @@ -105,7 +105,17 @@ | ||
| 105 | 105 | const { getModelFile } = await import('../runtime/model-store.js'); |
| 106 | 106 | const f = await getModelFile(url, onProgress); |
| 107 | 107 | if (f) return f; |
| 108 | - } catch (e) { console.warn('[elffuss] OPFS/broker no disponible, uso Cache Storage:', e); } | |
| 108 | + } catch (e) { | |
| 109 | + console.warn('[elffuss] OPFS/broker no disponible, uso Cache Storage:', e); | |
| 110 | + // Si lo que falló fue GUARDARLO en el disco del navegador (cuota, ventana | |
| 111 | + // privada…), se dice, igual que con Cache Storage más abajo: el progreso | |
| 112 | + // promete guardarlo, y callado el usuario se re-baja el modelo cada sesión | |
| 113 | + // sin saber por qué. Un fallo de red no es esto y no se anuncia así. | |
| 114 | + if (/Quota|NoModificationAllowed|InvalidModification|InvalidState|NotAllowed|Security|NotReadable/.test(e?.name || '')) { | |
| 115 | + onProgress(`No se pudo guardar el modelo en el disco del navegador (${e.name}): lo intento en la caché; si tampoco ` + | |
| 116 | + `se puede, habrá que descargarlo otra vez la próxima. Suele ser ventana privada o falta de espacio.`); | |
| 117 | + } | |
| 118 | + } | |
| 109 | 119 | |
| 110 | 120 | if (!self.caches) return url; |
| 111 | 121 | try { |