Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion config/main-blocking-helper-baseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -829,7 +829,7 @@
1 src/main/native-chat/agent-session-journal/context-epochs/journal-context-cursor.ts
12 src/main/native-chat/agent-session-journal/database/journal-database.ts
13 src/main/native-chat/agent-session-journal/database/journal-domain-database.ts # store-open tail fold (one-shot startup); same SQL already in main-blocking-sqlite-baseline
3 src/main/native-chat/agent-session-journal/database/journal-domain-migrations.ts # tail table create at store open (one-shot startup)
5 src/main/native-chat/agent-session-journal/database/journal-domain-migrations.ts # tail table create at store open (one-shot startup); worker-only: +2 create the retired-epoch pending table in a transaction on the journal SQL worker
8 src/main/native-chat/agent-session-journal/database/journal-domain-profile-import.ts
3 src/main/native-chat/agent-session-journal/database/journal-host-database.ts
40 src/main/native-chat/agent-session-journal/database/journal-legacy-reconcile.ts
Expand All @@ -846,6 +846,7 @@
7 src/main/native-chat/agent-session-journal/journal-domain-import.ts
1 src/main/native-chat/agent-session-journal/journal-domain-input-eligibility.ts
2 src/main/native-chat/agent-session-journal/journal-domain-item-display.ts
2 src/main/native-chat/agent-session-journal/journal-domain-maintenance.ts # worker-only: the retired prune settles its pending entry on the journal SQL worker
1 src/main/native-chat/agent-session-journal/journal-domain-queue-failures.ts
2 src/main/native-chat/agent-session-journal/journal-domain-queue-pauses.ts
6 src/main/native-chat/agent-session-journal/journal-domain-queue-reads.ts
Expand Down
1 change: 1 addition & 0 deletions config/main-blocking-sqlite-baseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
1 src/main/native-chat/agent-session-journal/database/journal-host-database.ts
32 src/main/native-chat/agent-session-journal/database/journal-legacy-reconcile.ts
18 src/main/native-chat/agent-session-journal/database/journal-legacy-source.ts
5 src/main/native-chat/agent-session-journal/database/journal-retire-pending.ts # worker-only: retired-epoch pending table, triggers and settle, run on the journal SQL worker
5 src/main/native-chat/agent-session-journal/database/journal-text-tail-schema.ts
12 src/main/native-chat/agent-session-journal/durable-rows/journal-row-table.ts
18 src/main/native-chat/agent-session-journal/history-import/journal-pi-active-branch.ts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type Database from '../../../sqlite/sync-database'
import { runJournalTransaction } from './journal-database'
import { JOURNAL_DOMAIN_SCHEMA_001 } from './journal-domain-schema-001'
import { JOURNAL_CONNECTOR_REPLIES_SCHEMA } from '../connector-replies/journal-connector-replies-schema'
import { ensureJournalRetirePending } from './journal-retire-pending'
import { ensureJournalTextTailTable } from './journal-text-tail-schema'

export const JOURNAL_DOMAIN_SCHEMA_VERSION = 2
Expand All @@ -25,6 +26,7 @@ export function migrateJournalDomainSchema(db: Database.Database): void {
ensureJournalStoredOutputColumn(db)
ensureJournalTextTailTable(db)
db.exec(JOURNAL_CONNECTOR_REPLIES_SCHEMA)
ensureJournalRetirePending(db, (run) => runJournalTransaction(db, run))
}

/** Added without a user_version change: released builds name their columns and never read it. */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import type Database from '../../../sqlite/sync-database'

// IF NOT EXISTS keeps old trigger bodies: rename a changed trigger and DROP the old name.
const PENDING_OBJECTS = [
'journal_retire_pending',
'journal_retire_pending_head_insert',
'journal_retire_pending_head_epoch',
'journal_retire_pending_item_epoch'
]

/**
* Chats that may hold rows of an epoch other than their head's. The retired-epoch sweep reads only
* these, so an idle store costs one empty read per pass instead of a visit to every chat. Triggers
* catch every head epoch change and every item written beside a ready head (a fork stage, which an
* abort or crash can strand), so writes from released builds are tracked too. Imports are covered
* by the head write that makes them ready. Created without a user_version change: released builds
* never read it. The caller passes its transaction runner: importing it here would close a cycle.
*/
export function ensureJournalRetirePending(
db: Database.Database,
inTransaction: (run: () => void) => void
): void {
const present = db
.prepare(
`SELECT count(*) AS present FROM sqlite_master WHERE name IN (SELECT value FROM json_each(?))`
)
.get(JSON.stringify(PENDING_OBJECTS))
if (Number(present?.present) === PENDING_OBJECTS.length) {
return
}
// Anything missing means epoch changes may have gone unseen, so every ready head is re-enqueued.
inTransaction(() =>
db.exec(`CREATE TABLE IF NOT EXISTS journal_retire_pending (
session_id TEXT PRIMARY KEY,
generation INTEGER NOT NULL
) WITHOUT ROWID;
CREATE TRIGGER IF NOT EXISTS journal_retire_pending_head_insert AFTER INSERT ON journal_chat_state
WHEN NEW.epoch IS NOT NULL
BEGIN
INSERT INTO journal_retire_pending(session_id,generation) VALUES(NEW.session_id,1)
ON CONFLICT(session_id) DO UPDATE SET generation=generation+1;
END;
CREATE TRIGGER IF NOT EXISTS journal_retire_pending_head_epoch
AFTER UPDATE OF epoch ON journal_chat_state
WHEN NEW.epoch IS NOT NULL AND NEW.epoch IS NOT OLD.epoch
BEGIN
INSERT INTO journal_retire_pending(session_id,generation) VALUES(NEW.session_id,1)
ON CONFLICT(session_id) DO UPDATE SET generation=generation+1;
END;
CREATE TRIGGER IF NOT EXISTS journal_retire_pending_item_epoch AFTER INSERT ON journal_items
WHEN EXISTS (SELECT 1 FROM journal_chat_state
WHERE session_id=NEW.session_id AND epoch IS NOT NULL AND epoch IS NOT NEW.epoch)
BEGIN
INSERT INTO journal_retire_pending(session_id,generation) VALUES(NEW.session_id,1)
ON CONFLICT(session_id) DO UPDATE SET generation=generation+1;
END;
INSERT INTO journal_retire_pending(session_id,generation)
SELECT session_id,1 FROM journal_chat_state WHERE epoch IS NOT NULL
ON CONFLICT(session_id) DO UPDATE SET generation=generation+1;`)
)
}

/** A chat enqueued again since its pass began keeps its entry for the next pass. */
export function settleJournalRetirePending(
db: Database.Database,
sessionId: string,
generation: number
): void {
db.prepare('DELETE FROM journal_retire_pending WHERE session_id=? AND generation=?').run(
sessionId,
generation
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { applyJournalSqlMaintenance, type JournalSqlMaintenance } from './journa
import { readJournalSqlDatabase } from './journal-sql-database-read'
import { JournalSqlBackgroundMaintenance } from './journal-sql-background-maintenance'
import { JournalSqlActivity } from './journal-sql-activity'
import { JournalForkStages } from './journal-fork-stages'
import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host'

const databases: Database.Database[] = []
const maintainers: JournalSqlBackgroundMaintenance[] = []
Expand Down Expand Up @@ -82,7 +84,8 @@ it('prunes proven retired epochs with atomic rollback while preserving incomplet
applyJournalSqlMaintenance(db, {
kind: 'domain-retired-prune',
sessionId: 'chat',
epoch: 'epoch'
epoch: 'epoch',
generation: 1
})
applyJournalSqlMaintenance(db, { kind: 'compaction-complete', now: 200 })
db.exec('ROLLBACK')
Expand All @@ -97,7 +100,12 @@ it('prunes proven retired epochs with atomic rollback while preserving incomplet
})
let more = true
while (more) {
const result = maintain(db, { kind: 'domain-retired-prune', sessionId: 'chat', epoch: 'epoch' })
const result = maintain(db, {
kind: 'domain-retired-prune',
sessionId: 'chat',
epoch: 'epoch',
generation: 1
})
if (!result || typeof result !== 'object' || !('more' in result)) {
throw new Error('expected page')
}
Expand Down Expand Up @@ -147,7 +155,32 @@ it('prunes proven retired epochs with atomic rollback while preserving incomplet
})
})

it('bounds a ready-head pass at its captured high key and skips changed or removed heads', () => {
function retiredPass(db: Database.Database): string[] {
const visited: string[] = []
let after: string | null = null
let through: string | null = null
for (;;) {
const page = readJournalSqlDatabase(db, { kind: 'retired-heads', after, through })
if (page.kind !== 'retired-heads') {
throw new Error('expected retired heads')
}
through = page.through
if (page.heads.length === 0) {
return visited
}
for (const head of page.heads) {
visited.push(head.sessionId)
let more = true
while (more) {
const result = maintain(db, { kind: 'domain-retired-prune', ...head })
more = typeof result === 'object' && result !== null && 'more' in result && result.more
}
after = head.sessionId
}
}
}

it('visits only chats that can hold retired rows since their last completed pass', () => {
const db = fixture()
const insert =
db.prepare(`INSERT INTO journal_chat_state(workspace_id,session_id,epoch,last_sequence,highest_fence)
Expand All @@ -157,75 +190,94 @@ it('bounds a ready-head pass at its captured high key and skips changed or remov
}
db.exec(`INSERT INTO journal_item_tombstones VALUES('chat','before','old',1),
('chat','epoch','current',1),('session-00','before','old',1)`)
retiredPass(db)
expect(db.prepare('SELECT session_id,epoch FROM journal_item_tombstones').all()).toEqual([
{ session_id: 'chat', epoch: 'epoch' }
])
expect(retiredPass(db)).toEqual([])

// A head that moves during a pass, and a chat that arrives behind its bound, wait for the next.
db.exec(`UPDATE journal_chat_state SET epoch='replacement' WHERE session_id='session-03'`)
const page = readJournalSqlDatabase(db, { kind: 'retired-heads', after: null, through: null })
expect(page).toMatchObject({ kind: 'retired-heads', through: 'session-19' })
if (page.kind !== 'retired-heads') {
throw new Error('expected ready heads')
}
expect(page.heads.map((head) => head.sessionId)).toEqual([
'chat',
'session-00',
'session-01',
'session-02',
'session-03',
'session-04',
'session-05',
'session-06',
'session-07',
'session-08',
'session-09',
'session-10',
'session-11',
'session-12',
'session-13',
'session-14'
])
expect(db.isTransaction).toBe(false)
insert.run('session-20')
db.exec(`UPDATE journal_chat_state SET epoch='replacement' WHERE session_id='chat';
DELETE FROM journal_chat_state WHERE session_id IN ('session-00','session-19')`)
for (const target of page.heads.slice(0, 2)) {
expect(maintain(db, { kind: 'domain-retired-prune', ...target })).toEqual({
kind: 'domain-retired',
deleted: 0,
more: false
})
throw new Error('expected retired heads')
}
expect(
db
.prepare('SELECT session_id,epoch FROM journal_item_tombstones ORDER BY session_id,epoch')
.all()
).toEqual([
{ session_id: 'chat', epoch: 'before' },
{ session_id: 'chat', epoch: 'epoch' },
{ session_id: 'session-00', epoch: 'before' }
])
expect(page.heads).toMatchObject([{ sessionId: 'session-03', epoch: 'replacement' }])
insert.run('session-99')
expect(
readJournalSqlDatabase(db, {
kind: 'retired-heads',
after: 'session-14',
after: 'session-03',
through: page.through
})
).toEqual({
kind: 'retired-heads',
through: 'session-19',
heads: [
{ sessionId: 'session-15', epoch: 'epoch' },
{ sessionId: 'session-16', epoch: 'epoch' },
{ sessionId: 'session-17', epoch: 'epoch' },
{ sessionId: 'session-18', epoch: 'epoch' }
]
})
expect(
readJournalSqlDatabase(db, {
kind: 'retired-heads',
after: 'session-18',
through: page.through
})
).toEqual({ kind: 'retired-heads', through: 'session-19', heads: [] })
expect(
readJournalSqlDatabase(db, { kind: 'retired-heads', after: null, through: null })
).toMatchObject({ kind: 'retired-heads', through: 'session-20' })
).toMatchObject({ heads: [] })
db.exec(`UPDATE journal_chat_state SET epoch='newer' WHERE session_id='session-03'`)
maintain(db, { kind: 'domain-retired-prune', ...page.heads[0]! })
expect(retiredPass(db)).toEqual(['session-03', 'session-99'])

// An item written between the read and the prune keeps the chat for the next pass.
const item =
db.prepare(`INSERT INTO journal_items(session_id,epoch,item_id,ordinal,revision,sequence,
sequence_index,owner_fence,payload_json) VALUES(?,?,?,1,1,1,0,1,'{}')`)
item.run('session-05', 'stale-1', 'a')
const stale = readJournalSqlDatabase(db, { kind: 'retired-heads', after: null, through: null })
if (stale.kind !== 'retired-heads') {
throw new Error('expected retired heads')
}
item.run('session-05', 'stale-2', 'b')
maintain(db, { kind: 'domain-retired-prune', ...stale.heads[0]! })
expect(retiredPass(db)).toEqual(['session-05'])

const stages = new JournalForkStages(db, '')
const begun = stages.apply(
{
kind: 'fork-stage-begin',
input: {
target: { sessionId: 'session-04', epoch: 'epoch', ownerToken: 'fork' },
identity: {
sessionId: 'session-04',
workspaceId: 'workspace',
hostId: LOCAL_EXECUTION_HOST_ID,
agent: 'codex',
providerHandle: null
},
fence: 1,
operationId: 'fork',
fingerprint: 'fork',
source: {
sessionId: 'chat',
throughItemId: 'body',
capability: 'tip',
retained: '',
location: {
executionHostId: LOCAL_EXECUTION_HOST_ID,
wslDistro: null,
workspaceId: 'workspace',
workspaceKind: 'folder'
},
submissionsToken: null
}
}
},
100
)
const [staged] = stages.epochs('session-04')
item.run('session-04', staged, 'staged')
db.exec(`INSERT INTO journal_retire_pending VALUES('forgotten',1)`)
expect(retiredPass(db)).toEqual(['forgotten', 'session-04'])
expect(retiredPass(db)).toEqual(['session-04'])
expect(db.prepare("SELECT epoch FROM journal_items WHERE session_id='session-04'").all()).toEqual(
[{ epoch: staged }]
)
if (!begun || !('token' in begun)) {
throw new Error('expected a fork stage')
}
stages.apply({ kind: 'fork-abort', token: begun.token }, 200)
expect(retiredPass(db)).toEqual(['session-04'])
expect(retiredPass(db)).toEqual([])
expect(db.prepare("SELECT epoch FROM journal_items WHERE session_id='session-04'").all()).toEqual(
[]
)
})

it('finishes a retired pass during activity while an already-started conversion is paused on idle', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { journalForkStageEpochs } from './journal-fork-stage-state'
import { settleJournalRetirePending } from './database/journal-retire-pending'
import type Database from '../../sqlite/sync-database'
import type { JournalStoredOutputCompaction } from './journal-stored-output-compaction'

export type JournalDomainMaintenance =
| { kind: 'domain-retired-prune'; sessionId: string; epoch: string }
| { kind: 'domain-retired-prune'; sessionId: string; epoch: string | null; generation: number }
| { kind: 'page-reclaim' }
| { kind: 'compaction-state' }
| { kind: 'compaction-complete'; now: number }
Expand Down Expand Up @@ -56,12 +57,18 @@ export const JOURNAL_EPOCH_TABLES: readonly {

export function pruneJournalDomainRetiredPage(
db: Database.Database,
target: { sessionId: string; epoch: string }
target: { sessionId: string; epoch: string | null; generation: number }
): JournalDomainMaintenanceResult {
const head = db
.prepare('SELECT epoch FROM journal_chat_state WHERE session_id=? AND epoch IS NOT NULL')
.get(target.sessionId)
if (head?.epoch !== target.epoch) {
if (!head) {
// No ready head proves which epoch is current; forgotten chats are discarded separately.
settleJournalRetirePending(db, target.sessionId, target.generation)
return { kind: 'domain-retired', deleted: 0, more: false }
}
if (head.epoch !== target.epoch) {
// The change that moved the head also re-enqueued it for the next pass.
return { kind: 'domain-retired', deleted: 0, more: false }
}
const held = journalForkStageEpochs(db, target.sessionId)
Expand Down Expand Up @@ -98,6 +105,10 @@ export function pruneJournalDomainRetiredPage(
}
}
}
// A live fork stage's rows aren't prunable yet; its chat stays pending until the stage ends.
if (held.length === 0) {
settleJournalRetirePending(db, target.sessionId, target.generation)
}
return { kind: 'domain-retired', deleted, more: false }
}

Expand Down
Loading
Loading