Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 13 additions & 8 deletions src/lib/admin/scheduler-pools-routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
slugifyPoolName,
} from '../db/repos/scheduler-pools-repo.mjs'
import { corsHeadersForRequest } from '../http/cors.mjs'
import { outboundSlotPurifyLedger } from '../identity/session-switch-purify.mjs'
import { resolveCredentialScheduleLevel } from '../pool/credential-weight.mjs'
import { resetSlotSessionState } from '../protocol/issued-tool-replay.mjs'
import {
Expand Down Expand Up @@ -1963,38 +1964,42 @@ export function createSchedulerPoolsHandler({
error: { message: '删除粘性绑定至少需要一个过滤条件', code: 'sticky_filter_required' },
})
}
// Only clear the targeted session's in-memory replay/epoch state when a
// specific session_id is deleted; never trigger global resets or disk wipes
// from ordinary scheduler sticky deletion.
// Only clear the targeted session's in-memory replay/epoch state and
// outbound purify ledger; never perform Node stickyRouter state I/O or
// trigger global resets / disk wipes from ordinary scheduler sticky deletion.
const purgeTargetedSessionState = () => {
const ledgerPurged = outboundSlotPurifyLedger.purgeByFilter(filter)
const targetSession = typeof filter.session_id === 'string' ? filter.session_id.trim() : ''
if (targetSession) {
resetSlotSessionState({ sessionId: targetSession })
}
return ledgerPurged
}

if (rt && typeof rt.deleteSticky === 'function') {
try {
const result = await rt.deleteSticky(filter)
const deleted = Number(result?.deleted) || 0
purgeTargetedSessionState()
const ledgerPurged = purgeTargetedSessionState()
const deleted = Math.max(Number(result?.deleted) || 0, ledgerPurged)
invalidatePoolsCache(['scheduler_sticky_bindings'])
return json(res, 200, {
ok: true,
deleted,
rust_deleted: result?.rust_deleted ?? 0,
db_deleted: result?.db_deleted ?? 0,
purify_ledger_purged: ledgerPurged,
data: { deleted },
})
} catch (err) {
return sendSchedulerError(res, err, 'delete_sticky_failed')
}
}
try {
const deleted = repo.deleteStickyBindings(filter)
purgeTargetedSessionState()
const dbDeleted = repo.deleteStickyBindings(filter)
const ledgerPurged = purgeTargetedSessionState()
const deleted = Math.max(dbDeleted, ledgerPurged)
invalidatePoolsCache(['scheduler_sticky_bindings'])
return json(res, 200, { ok: true, deleted, data: { deleted } })
return json(res, 200, { ok: true, deleted, purify_ledger_purged: ledgerPurged, data: { deleted } })
} catch (e) {
return json(res, httpStatusForPoolError(e), {
ok: false,
Expand Down
51 changes: 51 additions & 0 deletions src/lib/db/repos/sticky-repo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,57 @@ export class StickyRepo {
return this._deleteByAccount.run(accountId || '', vmId || '').changes
}

/**
* Delete sticky_sessions rows matching panel sticky filter criteria.
* Returns `{ deleted, keys }` so callers can invalidate L1/Redis caches and record reset tombstones.
*/
removeByFilter({
sessionId = null,
machineId = null,
identityId = null,
scopeKind = null,
nodeId = null,
accountId = null,
allowAll = false,
} = {}) {
if (allowAll) {
const keys = this._all.all().map((r) => r.key)
const changes = this.db.prepare('DELETE FROM sticky_sessions').run().changes
return { deleted: changes, keys }
}
const sid = String(sessionId || (scopeKind === 'session' ? identityId : '') || '').trim()
const mid = String(machineId || (scopeKind === 'machine' ? identityId : '') || '').trim()
const anyId = !scopeKind && identityId ? String(identityId).trim() : ''
const vm = String(nodeId || '').trim()
const acct = String(accountId || '').trim()
if (!sid && !mid && !anyId && !vm && !acct) return { deleted: 0, keys: [] }

const matchesRow = (row) => {
const k = String(row?.key || '')
if (vm && row?.vm_id !== vm) return false
if (acct && row?.account_id !== acct) return false
const matchSession = (target) =>
k === `sess:${target}` ||
k === `family2:${target}` ||
k.endsWith(`:sess:${target}`) ||
k.endsWith(`:family:${target}`) ||
k === target
const matchMachine = (target) =>
row?.device_id === target || k === `dev2:${target}` || k.endsWith(`:dev2:${target}`)
if (sid && !matchSession(sid)) return false
if (mid && !matchMachine(mid)) return false
if (anyId && !matchSession(anyId) && !matchMachine(anyId)) return false
return true
}

const keys = []
for (const row of this._all.all()) {
if (matchesRow(row)) keys.push(row.key)
}
for (const key of keys) this._delete.run(key)
return { deleted: keys.length, keys }
}

purgeExpired(now = Date.now()) {
return this._purge.run(now).changes
}
Expand Down
49 changes: 40 additions & 9 deletions src/lib/identity/identity-rewrite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ export const AGENT_SESSION_SEED = 'kin-claude-code-agent:'
/** Prefix so multi-turn headless scheduler sessions stay isolated from other derived ids. */
export const SCHEDULER_SESSION_SEED = 'kin-scheduler-session:'

/** Prefix so purified parent session ids on a switched slot never link back to the previous slot. */
export const PURIFIED_PARENT_SESSION_SEED = 'kin-purified-parent-session:'

/** Precedence order for inbound machine_id headers (never forged from IP/UA). */
export const MACHINE_ID_HEADER_KEYS = Object.freeze(['x-machine-id', 'x-kin-machine-id', 'x-kin-device-id'])

Expand Down Expand Up @@ -651,22 +654,46 @@ function resolvePassthroughOutboundSessionId(caller, opts) {
}

/**
* rebuild (default): same VM reuses the sticky outbound id; otherwise mint
* from inbound A (or the stable seed) + epoch. passthrough keeps the old
* official-keeps-A / unofficial-hash behavior.
* Derives a slot-isolated parent session UUID when a sub-agent hop switches slots,
* keeping parent/child correlation consistent inside the target slot while severing
* cross-slot linkage.
*/
export function derivePurifiedParentSessionId(
parentSessionId,
{ accountId = '', vmId = '', outboundSessionId = '' } = {},
) {
const parent = String(parentSessionId || '').trim()
if (!parent) return ''
const scope = `${String(accountId || '').trim()}|${String(vmId || '').trim()}|${String(outboundSessionId || '').trim()}`
return uuidFromSeed(`${PURIFIED_PARENT_SESSION_SEED}${scope}#${parent}`)
}

/**
* rebuild (default): same VM + same account reuses the sticky outbound id;
* otherwise mint from inbound A (or the stable seed) + epoch.
* passthrough keeps the old official-keeps-A / unofficial-hash behavior unless
* `slotSwitched` is true, in which case a fresh purified outbound session is
* always minted so the previous slot's session_id never leaks into the new slot.
*/
export function resolveOutboundSessionId(callerSession, opts = {}) {
const caller = String(callerSession || '').trim()
const mode = opts.mode || outboundSessionMode(opts.routing)
if (mode === 'passthrough') return resolvePassthroughOutboundSessionId(caller, opts)

const boundSessionId = String(opts.boundSessionId || '').trim()
const boundVmId = String(opts.boundVmId || '').trim()
const vmId = String(opts.vmId || '').trim()
const boundAccountId = String(opts.boundAccountId || '').trim()
const accountId = String(opts.accountId || '').trim()
const sameVm = Boolean(boundVmId && vmId && boundVmId === vmId)
if (boundSessionId && sameVm) return boundSessionId
const sameAccount = !boundAccountId || !accountId || boundAccountId === accountId
const slotSwitched = opts.slotSwitched === true
const sessionPurified = opts.sessionPurified === true || slotSwitched

if (boundSessionId && sameVm && sameAccount && !slotSwitched && (mode !== 'passthrough' || sessionPurified)) {
return boundSessionId
}

if (mode === 'passthrough' && !slotSwitched) return resolvePassthroughOutboundSessionId(caller, opts)

const accountId = String(opts.accountId || '').trim()
const discriminator =
opts.clientDiscriminator != null
? String(opts.clientDiscriminator)
Expand All @@ -676,9 +703,13 @@ export function resolveOutboundSessionId(callerSession, opts = {}) {
apiKeyId: opts.apiKeyId,
})
const firstUserIdentity = String(opts.firstUserIdentity || '')
const identity = caller || buildStableSessionSeed(accountId, discriminator, firstUserIdentity)
const baseIdentity = caller || buildStableSessionSeed(accountId, discriminator, firstUserIdentity)
if (slotSwitched && mode === 'passthrough') {
const purifiedSeed = `${accountId}|${vmId}|${baseIdentity || crypto.randomUUID()}`
return rebuildOutboundSession({ identity: purifiedSeed, epoch: opts.epoch ?? 'pending' })
}
if (caller || stableSessionMaterial(accountId, discriminator, firstUserIdentity)) {
return rebuildOutboundSession({ identity, epoch: opts.epoch ?? 'pending' })
return rebuildOutboundSession({ identity: baseIdentity, epoch: opts.epoch ?? 'pending' })
}
return crypto.randomUUID()
}
Expand Down
Loading
Loading