Skip to content

ui-sdk: native index publication intermittently refuses changed database or sidecar stamps #2878

Closed

Description

@schlessera

Context

During the native hosted proof's --observation-timing measurement (#2834) on main at 650caaf (pi, governed, UID 1000, 2,000 notes), the automatic index refresh queued after the timing turns failed, and the proof's final drain stopped on it:

NATIVE_AUTOMATIC_INDEX_COMPLETED: Error: stale maintenance output: .brain-index/brain.db-shm

Maintenance publication compares each output path's live entry with the one its worker started from and refuses a change (if (!equal(previous, live.entry, packages/ui-sdk/src/server/worker-native-output.ts:383). Those turns ran brain_search in governed pi workers, which open the live index read-only (function openRead, packages/ui-backend-pi/src/brain-access.ts:185-191). A read-only SQLite connection to a WAL database can still create or rewrite brain.db-shm, so a reader can change an index sidecar while maintenance prepares its output, and publication then refuses the whole refresh. This is a plausible cause, not an attributed one.

The default proof does not hit it; the timing mode runs 20 brain_search calls in quick succession while refreshes are queued.

Later recurrence (2026-10-25)

The #2853 native pi apply-timing cell (UID 1000, 2,000 notes) failed index publication in two of seven runs: one Native output changed before copy: .brain-index/brain.db-shm at automatic refresh drain, and one on .brain-index/brain.db at the same-turn search barrier (IndexFlushError, APPLY_TIMING_SEARCH_WAITED_FOR_INDEX). Every host apply succeeded. These are output-copy stamp failures, distinct from the original stale-input comparison; no common writer is attributed. Capture both input-versus-live and native-output-before-copy identities before choosing a fix. A sidecar-only exemption cannot be inferred to repair the database-file occurrence.

Scope

  • Attribute each refusal boundary: record which writer changed the input/live or native output entry, including both brain.db-shm and brain.db, between snapshot/copy/publication.
  • If it is a reader's shared-memory sidecar, decide how publication treats the index family's -shm (and -wal) so a concurrent reader cannot fail the refresh, without letting any other concurrent writer through.

Out of scope

Acceptance criteria

  • A test with a real concurrent read-only connection reproduces the refusal on the current code, or the receipt names the actual writer.
  • After the fix, that test publishes the refresh, and a test that changes any other output path between input and publication still refuses with stale maintenance output.

Verification

bun run test packages/ui-sdk packages/ui-server and bun scripts/prove-native-host.ts --backend=pi --app-uid=1000 --observation-timing.

Contract impact

None expected.

Found while measuring #2834.

2026-10-25 triage at main 827861e1fa71cd4a26b52f1ef0f96b849381acdf: Folded both later native-output-copy recurrence variants into the current reproduction brief. Preserve needs: repro: the reader-sidecar theory is unproven and does not explain the database-file variant.

2026-10-26 triage at main c670449d3bf1b0639e50ce554d728961f4313add: verified the current cited code and corrected literal source anchors/start lines. This navigation correction preserves historical receipts, decisions, scope, classification and unresolved prerequisites; no new runtime result or readiness is inferred.

Later matched base/head observation-timing recurrence — 2026-10-26

Reporter evidence from the retained recurrence:

2026-10-26 recurrence while validating #3001. The same pi UID 1000 --observation-timing cell, without fsync load, failed its final automatic-index drain on both trees:

  • Base c47483196f02c1098128207ce68c4f0de6b571ab, before the inbox migration: exit 1 after 114.2 seconds.
  • Inbox branch b9b7d099ba362838f22407902c9d3a4b9fc70cc6: exit 1 after 118.6 seconds.

Both report exactly:

NATIVE_AUTOMATIC_INDEX_COMPLETED: Error: stale maintenance output: .brain-index/brain.db-shm

The branch's observation artifact contains all 220 calls across 11 tool cases, with zero tool errors; the error comes later at queued refresh drain. Its default four-cell hosted matrices pass both without load and under three fsync writers, including the expected retained-index negative control and owned cleanup. The timing wrappers correctly await the now-asynchronous host bridge.

This confirms the existing failure on the base as well as the branch; it does not attribute which writer changed the sidecar or settle the publication policy. Input/live and native-output identities were not captured, so the current needs: repro qualification remains applicable.

2026-10-26 triage at main 2f10e0407769b685083c17a1c90bb43a060b94a0: Folded the additional source-qualified observation into the active brief. The failed identities remain uncaptured, so needs: repro and the existing guards remain.

Real-install recurrence — reported 2026-11-02

From the maintainer's report: a hosted 0.44.0 install with managed native storage (not a fixture) logged four index publication refusals in about one day of server uptime. All four name the -shm sidecar:

[brain] the keyed reindex after an application failed: stale maintenance output: .brain-index/brain.db-shm
[brain] governed index refresh failed: Error: stale maintenance output: .brain-index/brain.db-shm   (x3)

They happened in ordinary interactive sessions. In each, the agent applied several Markdown edits through edit_file and brain_update, and each edit queued an index update. User-visible effect: the edits were applied, but search served the old index until a later refresh succeeded. This failure therefore happens outside the timing proof: it affects search freshness in a real install. It is not only a fixture artifact.

Bounded SQLite-level observation — triage 2026-11-03

This checks the reader-sidecar premise and does not reproduce the publication refusal. Bun 1.4.2 bun:sqlite, local Linux, temporary directory, fictional one-row table. Each step recorded the size, mtimeNs and content SHA-256 of each file:

  1. A writer created a WAL database and closed it. brain.db-wal and brain.db-shm were then absent.
  2. One readonly: true connection opened and ran SELECT. This created brain.db-wal (0 bytes) and brain.db-shm (32 KiB). Both remained after that read-only connection closed.
  3. A second read-only SELECT rewrote brain.db-shm in place: its mtimeNs (and so its stamp) changed, but its content hash at rest was identical before and after.
  4. With a read-write connection held open, 20 read-only open/select/close cycles left the -shm stamp and content unchanged. When that read-write connection, the last one open, closed, SQLite deleted -wal and -shm again.
  5. brain.db was unchanged throughout.

Publication's stale-input check compares entries (if (!equal(previous, live.entry, packages/ui-sdk/src/server/worker-native-output.ts:383). For a file, an entry is its type, mode and content hash (async function inspect, same file:183-209). So the stale-input -shm signature is consistent with a reader creating an absent -shm, or a last read-write close deleting it, between the input snapshot and publication. An mtime-only rewrite like step 3 would not trip that check. Content sampled during a live transaction was not measured. The output-copy checks compare full stamps (Native output changed before copy, same file:428), so a step-3 style rewrite of the native output's -shm would trip them.

This evidence supports a sidecar mechanism for the -shm occurrences. It does not explain the brain.db output-copy variant, show which connection touched the live index in any failed run, or choose a publication policy. The script used temporary paths only and is not committed.

What still completes the repro: a product-path test that opens or closes a real connection on the live index between the input snapshot and publication (the first acceptance criterion), or a failed-run receipt naming the writer.

Related: #2921 attributes native automatic-index aborts on main (Native manager outcome is unknown … AbortError). That is a different signature, and no shared cause is claimed.

Triage 2026-11-03 at main 3d3516a0247702560c09c5a0889bdec39b8313fb: added the 2026-11-02 real-install -shm recurrence and its user-visible effect, plus a bounded SQLite observation: read-only connections create an absent -shm/-wal and touch its stamp, and the last read-write close deletes them. needs: repro remains for the product-path test or writer receipt; p2 kept, with a priority question raised in the triage comment.

Activity

  1. added
    type: fix
    area: ui-sdk
    priority: p2
    needs: repro
    on Oct 25, 2026
  2. schlessera commented on Oct 25, 2026

    @schlessera
    OwnerAuthor

    Seen twice more in the native pi --apply-timing cell (UID 1000, 2,000-note fixture) while proving #2853, at the same branch head, in 2 of 7 runs. Every host apply in both runs succeeded; the failures were in index publication:

    • once as reported here, the drained automatic refresh failing with Native output changed before copy: .brain-index/brain.db-shm (NATIVE_AUTOMATIC_INDEX_COMPLETED);
    • once as a variant on brain.db itself, at the same-turn brain_search barrier: the deferred targeted update failed with Native output changed before copy: .brain-index/brain.db, so the barrier refused (IndexFlushError) and the cell failed APPLY_TIMING_SEARCH_WAITED_FOR_INDEX.

    The second one is the same output-stamp check (packages/ui-sdk/src/server/worker-native-output.ts, the Native output changed before copy throw) hitting the main database file rather than its shared-memory sidecar.

  3. changed the title [-]ui-sdk: an automatic index refresh is refused as stale maintenance output when a reader touches brain.db-shm[/-] [+]ui-sdk: native index publication intermittently refuses changed database or sidecar stamps[/+] on Oct 25, 2026
  4. schlessera commented on Oct 25, 2026

    @schlessera
    OwnerAuthor

    2026-10-25 triage at main 827861e1fa71cd4a26b52f1ef0f96b849381acdf: Folded both later native-output-copy recurrence variants into the current reproduction brief. Preserve needs: repro: the reader-sidecar theory is unproven and does not explain the database-file variant.

  5. added this to the 0.45.0 milestone on Oct 25, 2026
  6. schlessera commented on Oct 26, 2026

    @schlessera
    OwnerAuthor

    2026-10-26 recurrence while validating #3001. The same pi UID 1000 --observation-timing cell, without fsync load, failed its final automatic-index drain on both trees:

    • Base c47483196f02c1098128207ce68c4f0de6b571ab, before the inbox migration: exit 1 after 114.2 seconds.
    • Inbox branch b9b7d099ba362838f22407902c9d3a4b9fc70cc6: exit 1 after 118.6 seconds.

    Both report exactly:

    NATIVE_AUTOMATIC_INDEX_COMPLETED: Error: stale maintenance output: .brain-index/brain.db-shm
    

    The branch's observation artifact contains all 220 calls across 11 tool cases, with zero tool errors; the error comes later at queued refresh drain. Its default four-cell hosted matrices pass both without load and under three fsync writers, including the expected retained-index negative control and owned cleanup. The timing wrappers correctly await the now-asynchronous host bridge.

    This confirms the existing failure on the base as well as the branch; it does not attribute which writer changed the sidecar or settle the publication policy. Input/live and native-output identities were not captured, so the current needs: repro qualification remains applicable.

  7. schlessera commented on Nov 2, 2026

    @schlessera
    OwnerAuthor

    Seen on a hosted 0.44.0 install with managed native storage (not a fixture). Within one day of server uptime, the server log has four index publication refusals:

    [brain] the keyed reindex after an application failed: stale maintenance output: .brain-index/brain.db-shm
    [brain] governed index refresh failed: Error: stale maintenance output: .brain-index/brain.db-shm   (x3)
    

    All four name the -shm sidecar. They happened during ordinary interactive sessions in which the agent applied several Markdown edits through edit_file and brain_update, each followed by a queued index update.

    Effect: the agent's edits were applied, but search kept serving the old index until a later refresh succeeded.

  8. schlessera commented on Nov 3, 2026

    @schlessera
    OwnerAuthor

    2026-11-03 triage at main 3d3516a0247702560c09c5a0889bdec39b8313fb: added the 2026-11-02 real-install recurrence to the body. A bounded SQLite observation (in the body) also supports the -shm mechanism: a read-only connection creates an absent -shm/-wal, and the last read-write close deletes them. Either change can trip the stale-input entry comparison. It does not explain the brain.db variant or name the writer in any failed run, so needs: repro stays.

    Priority question for the maintainer: this now affects search freshness in ordinary interactive use, not only the timing proof. Edits apply, but search serves the old index until a later refresh succeeds. Labels still say p2 with milestone 0.45.0. Raise to p1 if 0.45.0 should commit to fixing it; otherwise p2 stands. I left it at p2.

  9. added
    priority: p1
    and removed
    priority: p2
    on Nov 3, 2026
  10. schlessera commented on Nov 4, 2026

    @schlessera
    OwnerAuthor

    Reproduction findings — 2026-11-04

    Verdict: the original stale maintenance output: .brain-index/brain.db-shm defect is reproduced in the unmodified production publisher with a real concurrent read-only SQLite connection. This completes the first acceptance criterion for that refusal boundary. It does not attribute the two later Native output changed before copy variants.

    Inspected revision and environment

    Minimal conditions and observed result

    1. Use the real core openDatabase to seed one fictional row, then let that writer process exit. Unlike a bare new Database(...) probe, the product opener enables WAL persistence (db.fileControl(constants.SQLITE_FCNTL_PERSIST_WAL, 1), packages/core/src/lib/db.ts:117). The closed writer leaves the complete database/WAL/SHM family in place.
    2. Freeze the input family, prepare the real prepareNativeWorkerOutput, and update the stage's row using the real opener in a separate writer process. Let that process exit before publication.
    3. After the input snapshot, start a separate process using openDatabase(livePath, { readonly: true }), execute only SELECT value FROM odysseus, and hold that connection open through publication. This uses the same opener/options as pi's openRead (function openRead, packages/ui-backend-pi/src/brain-access.ts:185-191).
    4. Invoke the unmodified output.publish().

    Expected: a reader that changes no indexed document should not prevent publishing the prepared refresh. Observed: publication refuses the whole refresh, and the live index continues to return the old Ogygia row rather than staged Ithaca.

    Exact runtime boundary:

    Error: stale maintenance output: .brain-index/brain.db-shm
    at publish (packages/ui-sdk/src/server/worker-native-output.ts:383:92)
    

    The input/live brain.db and brain.db-wal hashes and stamps are identical. Both SHM files are 32,768 bytes with mode 0600, but the reader changes actual SHM content, not just its mtime: 162 bytes differed in the sampled failing run, including the word at byte offset 104 changing from 0 to 4294967295. Sample checkpoint/live SHM SHA-256:

    checkpoint 934d8181c9704e80dfd50c71b1b254fd8782bbbeae95867add6e09178a2848a0
    live       fd4c9fda9cd3f9ae7c962b0ddf37232294d55580e1aa165aa06129b8549389eb
    

    The script verifies the reader process is still alive through publication, checks the exact error, and checks that refusal published no index-family bytes. The only post-snapshot actor touching the live database is that real read-only connection; no fabricated sidecar bytes, timestamps, exceptions or product mutations are used.

    Bounded controls: five fresh fixtures per condition, 15 cases total. The after-snapshot reader refuses in 5/5; no intervening reader publishes in 5/5; priming the read-only connection before the input snapshot and reading again after it publishes in 5/5. Both successful controls verify a fresh read sees Ithaca. With --expect-refresh, the desired-behavior assertion exits 1 for the actual defect:

    AssertionError: READONLY_SEARCH_MUST_NOT_BLOCK_INDEX_REFRESH
    actual: Error: stale maintenance output: .brain-index/brain.db-shm
    expected: undefined
    

    These observations attribute a concrete reader-caused stale-input failure. The content comparison is the issue's cited if (!equal(previous, live.entry, packages/ui-sdk/src/server/worker-native-output.ts:383; file entries include a content hash (async function inspect, same file:183-209). Those anchors and the separate output-copy check (Native output changed before copy, same file:428) still match at the inspected SHA.

    Reusable reproduction

    From the inspected checkout, save the following block as /tmp/odysseus-2878-repro.ts. Its parent directory must be writable and on Btrfs: the copied acquisition fixture deliberately uses the repository's existing acquisition checks without patching filesystem predicates. This is the same testing boundary as packages/ui-sdk/tests/native-worker-publication.test.ts: the manager supplies copied acquisition/inspection metadata, while the actual publisher opens, hashes, copies and publishes real files. It does not qualify Btrfs snapshots, trusted OverlayFS, separate worker identity, the native manager or the complete hosted timing cell.

    bun install --frozen-lockfile
    bun run test ./packages/ui-sdk/tests/native-worker-publication.test.ts
    bun --no-env-file --preload ./scripts/test-network-child-preload.ts /tmp/odysseus-2878-repro.ts
    # Expected exit 0: 15 checked repro/control cases, final REPRO_AND_CONTROLS_PASS.
    bun --no-env-file --preload ./scripts/test-network-child-preload.ts /tmp/odysseus-2878-repro.ts --expect-refresh
    # Expected exit 1: READONLY_SEARCH_MUST_NOT_BLOCK_INDEX_REFRESH, with the exact SHM refusal.
    import * as fs from "node:fs";
    import assert from "node:assert/strict";
    import { join, resolve } from "node:path";
    import { createHash } from "node:crypto";
    const repo = process.cwd();
    const { openDatabase } = await import(resolve(repo, "packages/core/src/lib/db.ts"));
    const { prepareNativeWorkerStartupView } = await import(resolve(repo, "packages/ui-sdk/src/server/worker-startup-view.ts"));
    const { prepareNativeWorkerOutput } = await import(resolve(repo, "packages/ui-sdk/src/server/worker-native-output.ts"));
    assert(!process.env.BRAIN_UI_WORKER_IDENTITY_HELPER, "Use an unconfigured keyless fixture process");
    if (process.argv[2] === "sqlite") {
      const mode=process.argv[3], path=process.argv[4];
      const db=openDatabase(path,{readonly:mode === "read" || mode === "hold"});
      if(mode === "seed") {db.run("CREATE TABLE odysseus(value TEXT)");db.run("INSERT INTO odysseus VALUES('Ogygia')");}
      if(mode === "update") db.run("UPDATE odysseus SET value='Ithaca'");
      if(mode === "read" || mode === "hold") console.log(JSON.stringify(db.query("SELECT value FROM odysseus").get()));
      if(mode === "hold") await new Response(Bun.stdin).text();
      db.close();process.exit(0);
    }
    function sql(mode:string,path:string) {
      const result=Bun.spawnSync([process.execPath,"--no-env-file","--preload",resolve(repo,"scripts/test-network-child-preload.ts"),import.meta.path,"sqlite",mode,path],
        {cwd:repo,env:{PATH:process.env.PATH},stdout:"pipe",stderr:"pipe"});
      assert.equal(result.exitCode,0,result.stderr.toString());
      return result.stdout.toString().trim();
    }
    async function holdReader(path: string) {
      const child=Bun.spawn([process.execPath,"--no-env-file","--preload",resolve(repo,"scripts/test-network-child-preload.ts"),import.meta.path,"sqlite","hold",path],
        {cwd:repo,env:{PATH:process.env.PATH},stdin:"pipe",stdout:"pipe",stderr:"pipe"});
      const stdout=child.stdout.getReader(), stderr=new Response(child.stderr).text();
      const stop=async()=>{child.stdin.end();const code=await child.exited;await stdout.cancel();assert.equal(code,0,await stderr);};
      let timer: ReturnType<typeof setTimeout> | undefined;
      try {
        const first=await Promise.race([stdout.read(),new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(Error("READONLY_READY_TIMEOUT")),5000);})]);
        assert.equal(new TextDecoder().decode(first.value).trim(),JSON.stringify({value:"Ogygia"}));
        assert.equal(child.exitCode,null,"REAL_READONLY_PROCESS_STILL_ALIVE");
        return {stop,child};
      } catch(error) {await stop();throw error;} finally {clearTimeout(timer);}
    }
    const sourceUuid = "11111111111141118111111111111790", uuid = "22222222222242228222222222221790";
    const family = ["brain.db", "brain.db-wal", "brain.db-shm", "brain.db-journal"];
    const rel = ".brain-index/brain.db";
    function identity(root: string) {
      return Object.fromEntries(family.map(name => {
        const path = join(root, ".brain-index", name);
        if (!fs.existsSync(path)) return [name, null];
        const st = fs.statSync(path, { bigint: true }), bytes = fs.readFileSync(path);
        return [name, { bytes: bytes.length, mode: Number(st.mode & 0o777n),
          sha256: createHash("sha256").update(bytes).digest("hex"),
          stamp: [st.dev,st.ino,st.mode,st.size,st.mtimeNs,st.ctimeNs].join(":"),
          ...(name.endsWith("-shm") ? { readMark1: bytes.readUInt32LE(104) } : {}) }];
      }));
    }
    async function run(kind: "no-reader" | "reader-after-snapshot" | "reader-primed-before-snapshot", ordinal: number) {
      // Ordinary copied acquisition fixture, as in native-worker-publication.test.ts.
      // The publisher and all SQLite I/O are production code; no native-storage qualification.
      const store = fs.mkdtempSync(resolve(repo, "..", "odysseus-2878-")), brain = join(store, "brain");
      assert.equal(fs.statfsSync(store).type, 0x9123683e, "Fixture parent must be on Btrfs");
      fs.mkdirSync(brain);
      sql("seed",join(brain,rel));
      if (kind === "reader-primed-before-snapshot") {
        assert.equal(sql("read",join(brain,rel)),JSON.stringify({value:"Ogygia"}));
      }
      const baseline = identity(brain);
      const checkpoints = new Map<string,string>(); let checkpointId = "";
      const start = fs.readFileSync(`/proc/${process.pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[19]!;
      const manager = {
        async checkpoint(id: string) {
          const path = join(store, ".brain-native/checkpoints", id);
          fs.cpSync(brain, path, { recursive: true }); checkpoints.set(id,path); checkpointId = id;
          return {id,path,sourceUuid,uuid,fsid:"11111111-1111-4111-8111-111111111790",rootId:"257",transaction:"8",readOnly:true as const};
        },
        async release(id: string) { fs.rmSync(checkpoints.get(id)!,{recursive:true,force:true}); return {id,state:"deleted" as const}; },
        async prepareStage(id: string, lower: string, allowanceBytes: number) {
          const path = join(store,".brain-native/stages",id);
          fs.mkdirSync(path,{recursive:true});fs.cpSync(checkpoints.get(lower)!,join(path,"merged"),{recursive:true});
          const st=fs.statSync(path,{bigint:true});
          return {id,path,checkpointId:lower,checkpointUuid:uuid,sourceUuid,allowanceBytes,namespacePid:process.pid,namespaceStart:start,
            appUid:process.getuid!(),appGid:process.getgid!(),rootDevice:String(st.dev),rootInode:String(st.ino)};
        },
        async inspectStage() {
          return {checkpointId,checkpointUuid:uuid,changes:(async function*(){
            for(const name of family) yield {pathHex:Buffer.from(`.brain-index/${name}`).toString("hex"),kind:"entry" as const};
          })(),completed:Promise.resolve({exitCode:0 as const,bytes:0})};
        },
        async releaseStage(id: string) {fs.rmSync(join(store,".brain-native/stages",id),{recursive:true,force:true});return {id,state:"deleted" as const};},
      };
      let held: Awaited<ReturnType<typeof holdReader>> | undefined;
      let view: Awaited<ReturnType<typeof prepareNativeWorkerStartupView>> | undefined;
      let output: Awaited<ReturnType<typeof prepareNativeWorkerOutput>> | undefined;
      try {
        view=await prepareNativeWorkerStartupView(brain,manager);
        output=await prepareNativeWorkerOutput(brain,{startupView:view,areas:[".brain-index"]});
        sql("update",join(output.output.source,rel));
        const staged=identity(output.output.source);
        if(kind === "reader-after-snapshot") held=await holdReader(join(brain,rel));
        if(kind === "reader-primed-before-snapshot") assert.equal(sql("read",join(brain,rel)),JSON.stringify({value:"Ogygia"}));
        const live=identity(brain), checkpoint=identity(view.root);
        let failure: unknown;
        try {await output.publish();} catch(error) {failure=error;}
        const error=failure instanceof Error?failure.message:String(failure ?? "published");
        if(held) assert.equal(held.child.exitCode,null,"READONLY_CONNECTION_OVERLAPPED_PUBLICATION");
        const beforeShm=fs.readFileSync(join(view.root,rel+"-shm")), liveShm=fs.readFileSync(join(brain,rel+"-shm"));
        const byteChanges=[...beforeShm.keys()].filter(i=>beforeShm[i]!==liveShm[i]).map(i=>({offset:i,before:beforeShm[i],live:liveShm[i]}));
        console.log(JSON.stringify({kind,ordinal,error,readonlyAlive:held?.child.exitCode === null,baseline,checkpoint,live,staged,byteChanges,
          stack:failure instanceof Error?failure.stack?.split("\n").slice(0,3):undefined}));
        if(kind === "reader-after-snapshot") {
          if(process.argv.includes("--expect-refresh")) assert.equal(failure,undefined,"READONLY_SEARCH_MUST_NOT_BLOCK_INDEX_REFRESH");
          assert.equal(error,"stale maintenance output: .brain-index/brain.db-shm","REAL_READONLY_CONNECTION_REPRODUCES_PUBLICATION_REFUSAL");
          assert.notEqual(live["brain.db-shm"]!.sha256,checkpoint["brain.db-shm"]!.sha256,"READONLY_SELECT_CHANGED_LIVE_SHM_CONTENT");
          assert.equal(live["brain.db"]!.sha256,checkpoint["brain.db"]!.sha256);
          assert.equal(live["brain.db-wal"]!.sha256,checkpoint["brain.db-wal"]!.sha256);
          const after=identity(brain);
          for(const name of family) assert.deepEqual(after[name],live[name],"REFUSAL_PUBLISHED_NO_INDEX_BYTES");
          assert.equal(sql("read",join(brain,rel)),JSON.stringify({value:"Ogygia"}),"LIVE_INDEX_REMAINS_OLD");
        } else {
          assert.equal(failure,undefined,"CONTROL_REFRESH_PUBLISHES");
          assert.equal(sql("read",join(brain,rel)),JSON.stringify({value:"Ithaca"}),"CONTROL_REFRESH_IS_VISIBLE");
        }
      } finally {
        try {await held?.stop();} finally {try {await output?.cleanup();} finally {try {await view?.cleanup();} finally {fs.rmSync(store,{recursive:true,force:true});}}}
      }
    }
    for(let i=1;i<=5;i++) for(const kind of ["no-reader","reader-after-snapshot","reader-primed-before-snapshot"] as const) await run(kind,i);
    console.log(JSON.stringify({result:"REPRO_AND_CONTROLS_PASS",cases:15}));

    Attempts, limits and next step

    • The existing publisher suite passed: 6 tests, 19 assertions, 0 failures. The reproduction/control script exited 0 on 15 cases; the desired-behavior assertion exited 1 on the exact product error above.
    • An initial plain SQLite premise probe was extended to use the actual core opener after discovering WAL persistence. An initial all-in-one-process harness published but failed its fresh-value control; that was not counted as a valid reproduction. The retained script isolates seed/update/read work in real processes and verifies both publication and freshness controls. One preliminary invocation named a nonexistent preload; that startup failure was corrected and supplies no defect evidence.
    • This bounded run exercises the core opener and real native-output publication algorithm, with a synthetic one-row database and copied acquisition metadata. It does not run brain_search, the full indexer, the 2,000-note hosted proof, provider traffic or any production install. No assertion about those complete flows is inferred from it, and no live-provider evidence is necessary to establish this reader/publication mechanism.
    • The two output-copy stamp failures, including the brain.db variant, remain unattributed. The independent native automatic-index abort signature in ci: attribute recurring native automatic-index aborts on main #2921 remains separate. No common writer/cause or sidecar-only remedy is claimed.
    • Next implementation work: turn this controlled interleaving into permanent regression coverage, choose a safe index-family publication treatment within the existing brief, preserve refusal for unrelated concurrent output changes, and separately instrument the before-copy identities for the later variants. The issue stays open; no fix or publication-policy ruling is supplied by this triage.

    Readiness: the original SHM refusal now has the requested real-reader product-path reproduction. Remove needs: repro; if the fresh issue read still has no other needs: label, add agent-ready. Preserve type: fix, area: ui-sdk, priority: p1, milestone 0.45.0, state and assignments. Other-variant attribution and post-fix/native verification remain implementation work under this issue, not results claimed here.

  11. added
    agent-ready
    and removed
    needs: repro
    on Nov 4, 2026
  12. self-assigned this
    on Nov 15, 2026
  13. schlessera commented on Nov 15, 2026

    @schlessera
    OwnerAuthor

    Claimed for implementation. Claim token: claim-10321159. Branch: fix/2878-index-sidecar-publication.

    closure reports only (no direct path overlap with worker-native-output.ts): #3054 #3056 #3059 #3069 #3116 #3393 #3437 #3464 #3581 #3622 #3806 #4002

  14. schlessera commented on Nov 15, 2026

    @schlessera
    OwnerAuthor

    Delivered by #4011, squash 5af68976988140d8d916f74d7342959a4cc4e66d on main (verified to be an ancestor of origin/main). Candidate run 43721145240 passed. The squash's main CI run 43723553262 was still in progress at merge.

    • Acceptance criteria. Before the fix, a real read-only connection, held in its own process on the live index, refused publication with stale maintenance output: .brain-index/brain.db-shm. After the fix it publishes, and a new connection reads the refresh. A concurrent index writer, a note writer and a link planted over -shm all still refuse. The PR has the failing-first and mutation receipts.
    • Ruling (recorded in docs/decisions/governed-writable-workers.md). The wal-index follows its database: it is never compared or copied, and a fresh empty file replaces it whenever brain.db or brain.db-wal publishes. Leaving the live -shm in place was rejected: a new connection that pairs the published WAL with a wal-index an earlier reader still holds fails with SQLITE_IOERR_SHORT_READ.
    • Follow-ups. ui-sdk: copy-staged maintenance publication refuses a refresh when a reader touches the index wal-index #4009 covers copy-staged publication without native storage, which has the same comparison. ui-sdk: attribute the native stage writer behind 'Native output changed before copy' on brain.db #4010 covers attributing the Native output changed before copy: .brain-index/brain.db timing variant. Those refusals now name the inspected and found stamps.
    • Not run here. The native prove-native-host.ts --observation-timing cell needs the native manager host.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

agent-readyarea: ui-sdkpriority: p1type: fix

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions