Skip to content

ui-server: canonical dialogue drain and withhold miss fresh-owner aliases #3351

Open

Description

@schlessera

Out of scope

Admission thresholds, persisted schema/semantics, wire changes, global journal-drain redesign, alias lookup redesign, provider-history edits, weaker storage settlement budgets, releasing uncertain native writes, and unrelated archives. Preserve the selected membership rule from #3215 rather than inventing a new ownership policy.

Context

A real keyless file-backed SQLite-writer reproduction at main 1619741f291f525d17cde4970a5ada40644117c1 confirms both boundaries miss a fresh provisional reference that has already reserved the canonical archive's session. The original source-reading lead is now reproduced; no product fix is implemented by this triage.

  • (archivePending, packages/ui-server/src/ws/dialogue.ts:295-310) already combines equal IDs or reserved sessions transitively under ui-server: share pending admission across fresh-owner alias binding #3215/fix(ui-server): share pending admission across fresh-owner alias binding #3352.
  • (private ownerWrites, packages/ui-server/src/ws/dialogue.ts:339-341) still filters pending references by current ID alone. (async settleOwner, packages/ui-server/src/ws/dialogue.ts:343-355) can therefore report a completed canonical drain while the alias has native writes outstanding.
  • (private withholdOwner, packages/ui-server/src/ws/dialogue.ts:356-362) uses the same current-ID-only predicate. Expiring only the canonical drain deadline leaves the newer alias's callbacks publishable after their genuine writes commit.
  • Real consumers include the storage-failure handling at (void this.dialogue.settleOwner, packages/ui-server/src/ws/host.ts:448-454) and (void this.host.dialogue.settleOwner, packages/ui-server/src/ws/conversation.ts:1170-1176). This reproduction exercises the journal/catalog boundary; it does not claim a live-provider or end-to-end user incident.

Binding behavior is recorded in docs/decisions/live-conversation.md: owner-scoped callbacks drain before close, genuine failure coverage survives adoption, and unrelated owners stay independent. docs/decisions/sqlite-write-worker.md preserves ordered native writes and ownership through genuine settlement.

Observed reproduction — 2026-11-08

Bun 1.4.4 (38afee6c8), independently installed frozen dependencies, unmodified production source. Six temporary cases ran through bun run test and its ordinary offline guard: 2 pass / 4 fail, 22 assertions, exit 1, 1.254 seconds test phase.

Each case creates a real file-backed UI database, openSqliteWriter with offloop === true, the production session catalog and DialogueJournal. The existing test-only holdUntilReleased procedure holds the real writer. There are two routes: inactive-conversation bind and adoptTurn followed by a real session-info frame.

Boundary Equal-ID control Inactive bind Adopt turn
Drain before releasing native writer Remains pending Resolves early Resolves early
Published pages after only canonical drain expiry and later real settlement Unrelated sparta only Alias ithaca, then sparta Two ithaca pages, then sparta

At each premature drain, the target is troy, the pending reference is ithaca, both reserve session voyage, the native hold is live, and the database contains zero dialogue records. Both cases fail CANONICAL_DRAIN_MUST_WAIT_FOR_FRESH_ALIAS_NATIVE_WRITE (expected false, actual true).

For withholding, the existing storageDeadlineClock.captureLatest() expires only the canonical drain's production budget; the alias and unrelated-owner write deadlines stay unexpired. After releasing the native writer, both aliases publish, failing CANONICAL_WITHHOLD_SUPPRESSES_ALIAS_BUT_PRESERVES_UNRELATED_OWNER. Real records still commit under canonical troy; unrelated sparta publishes. This establishes missed logical withholding, not stopped writes or lost authoritative data. All six fixtures release/join their writer and remove only their owned database directory, including the four failing cases. Complete global timer descriptors are restored.

The linked reproduction comment contains the portable temporary fixture and command. Retain these failing controls as the implementation baseline; no repaired/restored run is claimed.

Scope

Make owner-specific draining, ordered explicit refusals, close and logical withholding cover the same canonical archive membership already enforced by admission, including fresh references whose provisional IDs have not changed. Keep native write/capacity ownership intact until actual settlement and preserve independence of unrelated archives.

Acceptance criteria

  • Both inactive-bind and adopt-turn routes retain the native held-writer reproduction. A canonical drain remains pending while an alias write is genuinely outstanding; it settles after release/commit, or reports the existing bounded indeterminate outcome.
  • An indeterminate canonical drain withholds every relevant alias callback, including callbacks whose own newer deadline has not expired. Their real writes remain owned and may later commit; they cannot re-enter the withheld live scope.
  • Equal IDs, equal reserved sessions and transitive archive membership behave consistently with admission. Unrelated owners can drain and publish independently; no global drain replaces the owner-specific boundary.
  • Close ordering and explicitly refused callbacks use the same membership, without deadlocking on the close operation itself or losing retained failure coverage after adoption.
  • Native writer and queued ownership are joined on success/failure, with exact persisted canonical rows and no replay/duplicate effects. Existing admission limits, storage budgets and authority remain unchanged.
  • Removing the membership correction makes the named drain/withhold assertions fail for these reasons; restoration passes. Cover every matching ID-only membership instance in the file before calling the class repaired.

Verification

Place the attached temporary fixture at tmp/triage-3351.test.ts in an isolated frozen checkout and run bun run test ./tmp/triage-3351.test.ts. For implementation, promote focused runtime regressions into the owning package and run:

bun run test packages/ui-server/tests/dialogue-owner-drain.test.ts packages/ui-server/tests/dialogue-queue-adoption.test.ts packages/ui-server/tests/dialogue-storage.test.ts
bun run typecheck
bun run lint
bun run check:pr --base origin/main

Keep the failing baseline and restored mutation receipts. No provider credentials, external network, paid call, browser or hosted deployment is needed to reproduce this journal boundary.

Contract impact

Internal correctness repair under existing owner-scoped guarantees; no supported schema, wire, CLI or frontmatter change is requested. Published ui-server behavior needs the normal patch changeset. Any newly discovered contract change requires separate classification before implementation.

Triage 2026-11-08: replaced the unconfirmed lead with a real six-cell native-writer receipt and an implementation-ready brief; remove needs: repro. Preserve the maintainer's existing p3 ranking. Standalone: this repairs the shared typed/voice journal ownership boundary, broader than own-chat deletion or one voice interaction; related epics remain references rather than a forced parent.

Activity

  1. added
    type: fix
    area: ui-server
    priority: p3
    needs: repro
    on Nov 2, 2026
  2. changed the title [-]ui-server: check whether dialogue drain and withhold miss a fresh-owner alias reference[/-] [+]ui-server: canonical dialogue drain and withhold miss fresh-owner aliases[/+] on Nov 8, 2026
  3. schlessera commented on Nov 8, 2026

    @schlessera
    OwnerAuthor

    Reproduction — 2026-11-08, main 1619741f291f525d17cde4970a5ada40644117c1.

    A real file-backed worker reproduces both claimed boundaries on both routes: 2 equal-ID controls pass; 4 fresh-alias assertions fail. The issue body records the exact expected/actual observations, runtime and limits. No production file was changed. Keep this fixture temporary during triage; promote its proof in the eventual fix.

    From an isolated checkout with frozen dependencies, save the following as tmp/triage-3351.test.ts and run bun run test ./tmp/triage-3351.test.ts. Expected on the inspected source: 2 pass, 4 fail at the two named assertions; all six cleanup markers print. This is an observed failing baseline, not a repaired passing suite.

    import { expect, test } from 'bun:test';
    import { mkdtempSync, rmSync } from 'node:fs';
    import { tmpdir } from 'node:os';
    import { join } from 'node:path';
    import { createUiDb } from '../packages/ui-server/src/db/client.ts';
    import { openSqliteWriter } from '../packages/ui-server/src/db/write-worker.ts';
    import { createOffloopActivityStore } from '../packages/ui-server/src/activity/store-writes.ts';
    import { createSessionCatalog } from '../packages/ui-server/src/ws/session-catalog.ts';
    import { DialogueJournal } from '../packages/ui-server/src/ws/dialogue.ts';
    import { StorageSettlementIndeterminate } from '../packages/ui-server/src/db/settlement.ts';
    import { storageDeadlineClock } from '../packages/ui-server/tests/helpers/storage-deadline-clock.ts';
    import * as controls from '../packages/ui-server/tests/helpers/dialogue-test-writes.ts';
    const opening={conversationId:'ithaca',principalId:'odysseus',epoch:1,providerId:'gemini-live'};
    const checkpoint=()=>new Promise<void>(resolve=>setImmediate(resolve));
    const evidence=(id:string)=>({kind:'voice',conversationId:id,epoch:1,providerId:'gemini-live',event:{kind:'unassigned_input_fragment',sequence:0,text:'The mast is ready.',timing:{kind:'unavailable'},finalization:'unknown'}} as any);
    async function fixture(){
     const dir=mkdtempSync(join(tmpdir(),'odysseus-3351-')),db=createUiDb(join(dir,'ui.db')),writer=openSqliteWriter(db);
     const catalog=createSessionCatalog(()=>db,undefined,undefined,{writer,pricing:{resolve:()=>null},store:createOffloopActivityStore(db,writer)});
     const control=writer.channel({url:controls.url,setup:controls.setup},{}),pages:any[]=[],failures:any[]=[];
     const journal=new DialogueJournal(catalog,page=>pages.push(page),(owner,cause)=>failures.push({id:owner.id,cause}));
     const gate=new Int32Array(new SharedArrayBuffer(8));let held:Promise<unknown>|undefined;
     const release=()=>{Atomics.store(gate,0,1);Atomics.notify(gate,0);};
     return {db,writer,catalog,journal,pages,failures,gate,release,
     async hold(){held=control.call('holdUntilReleased',gate);const deadline=Date.now()+2000;while(!Atomics.load(gate,1)){if(Date.now()>deadline)throw Error('NATIVE_WRITER_DID_NOT_ENTER_HOLD');await Bun.sleep(1);}expect(writer.offloop).toBe(true);},
     async close(){release();await held;await journal.settled();await catalog.settled!();await control.close();await writer.close();db.close();rmSync(dir,{recursive:true,force:true});console.log('OWNED_WRITER_RELEASED_JOINED_AND_REMOVED');}};
    }
    async function prepare(f:Awaited<ReturnType<typeof fixture>>,route:string){
     if(route!=='equal-id'){await f.catalog.dialogueOpen!(opening);await f.catalog.dialogueClose!('ithaca','odysseus',1,false);}
     const target=(await f.journal.open({...opening,conversationId:'troy',sessionId:'voyage'}))!;
     const unrelated=(await f.journal.open({...opening,conversationId:'sparta',sessionId:'other-voyage'}))!;
     if(route==='equal-id')await f.journal.open({...opening,conversationId:'pylos',sessionId:'voyage'});
     return {target,unrelated};
    }
    function enqueueAlias(f:Awaited<ReturnType<typeof fixture>>,route:string){
     if(route==='equal-id'){f.journal.voice('pylos',evidence('pylos'));return;}
     if(route==='inactive-bind')f.journal.bind('ithaca','odysseus','voyage');
     else {f.journal.adoptTurn('mast-turn','ithaca','odysseus');f.journal.backend({type:'session_info',sessionId:'voyage',isNew:false,turnId:'mast-turn'} as any);}
     f.journal.backend({type:'text_delta',sessionId:'voyage',turnId:'mast-turn',text:'The mast is ready.'} as any);
    }
    for(const route of ['equal-id','inactive-bind','adopt-turn'])test('3351 canonical drain waits for held writer route='+route,async()=>{
     const f=await fixture();
     try{
      const {target}=await prepare(f,route);await f.hold();enqueueAlias(f,route);
      let done=false;const drain=f.journal.settleOwner(target).then(()=>{done=true;});
      await checkpoint();await checkpoint();
      const pending=[...(f.journal as any).ownerPending.keys()].map((o:any)=>({id:o.id,session:o.session_id}));
      const persisted=f.db.query('SELECT COUNT(*) AS n FROM dialogue_records').get();
      console.log(JSON.stringify({route,boundary:'drain-before-release',targetId:target.id,pending,drainResolved:done,nativeHoldLive:Atomics.load(f.gate,1)===1&&Atomics.load(f.gate,0)===0,persisted}));
      expect(done,'CANONICAL_DRAIN_MUST_WAIT_FOR_FRESH_ALIAS_NATIVE_WRITE').toBe(false);
      f.release();await drain;await f.journal.settled();
      expect(f.db.query('SELECT DISTINCT owner_id FROM dialogue_records').all()).toEqual([{owner_id:'troy'}]);
     }finally{await f.close();}
    });
    for(const route of ['equal-id','inactive-bind','adopt-turn'])test('3351 canonical withhold covers newer alias route='+route,async()=>{
     const f=await fixture();let clock:ReturnType<typeof storageDeadlineClock>|undefined;
     try{
      const {target}=await prepare(f,route);await f.hold();clock=storageDeadlineClock();
      f.journal.voice('troy',evidence('troy'));
      const draining=f.journal.settleOwner(target).catch(e=>e),expireDrain=clock.captureLatest();
      enqueueAlias(f,route);f.journal.voice('sparta',evidence('sparta'));
      const refs=[...(f.journal as any).ownerPending.keys()].map((o:any)=>({id:o.id,session:o.session_id}));
      expireDrain();expect(await draining).toBeInstanceOf(StorageSettlementIndeterminate);
      expect(Atomics.load(f.gate,0),'REAL_WRITER_IS_STILL_HELD_AT_LOGICAL_TIMEOUT').toBe(0);
      f.release();await f.journal.settled();
      const ownerIds=f.pages.map(p=>p.ownerId),rows=f.db.query('SELECT DISTINCT owner_id FROM dialogue_records ORDER BY owner_id').all();
      console.log(JSON.stringify({route,boundary:'after-canonical-withhold-and-real-settlement',refs,publishedOwnerIds:ownerIds,persistedOwners:rows,failures:f.failures}));
      expect(rows,'REAL_WRITES_REMAIN_OWNED_AND_EVENTUALLY_COMMIT').toEqual([{owner_id:'sparta'},{owner_id:'troy'}]);
      expect(ownerIds,'CANONICAL_WITHHOLD_SUPPRESSES_ALIAS_BUT_PRESERVES_UNRELATED_OWNER').toEqual(['sparta']);
     }finally{await f.close();clock?.restore();}
    });
  4. added
    agent-ready
    and removed
    needs: repro
    on Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-readyarea: ui-serverpriority: p3type: fix

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions