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
1 change: 1 addition & 0 deletions changelog.d/96.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Keep direct spoken requests intact when older ASR lanes deliver delayed finals, without losing speech cancellation.
10 changes: 8 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,14 @@ Owns `server/src/actions.ts`, `server/src/executor.ts`, `server/src/research.ts`
A retried job that finds actions with its ID does not plan again; it reports them as `already_requested` with the research it stored.
When the plan has both, `planWork` runs again over only the planned actions, with the cited research in a delimited untrusted block; research may fill only content fields (subject, body, notes and the like), and a pass that changes any other argument, adds an action or drops one is rejected, so no action is requested. A refused research requests no action either; both are reported as the `outcome` of a succeeded job.
Web research reserves one of the workspace's `SANCTUM_PAID_RESEARCH_CALLS_PER_DAY` and the install's `SANCTUM_PAID_RESEARCH_CALLS_PER_DAY_TOTAL` paid calls in `paid_model_calls` before sending, records the provider's token usage (also for a billed call that ends incomplete), stores a `research` artifact once per job, and adds an `external` `research_observation` citing it; a spent allowance is a `refused` result, a rate limit pauses the job, a dropped proposal is reported in `dropped` with its reason, and nothing to do is a reported `outcome`.
- Known ASR timing limit: delayed finals across lane rotation can split a request prematurely or be ignored during an active reply.
Sorting only restores segments collected before turn completion; the authorized follow-up is [#96](https://github.com/i098/sanctum/issues/96).
- Pending live finals are deduplicated by ID and ordered by source samples before source-gap boundaries split requests.
A gap of at least `engineeringDefaults.speech.endOfTurnMs` separates turns.
Coverage completes each turn once it extends that far past its end, even while later speech remains pending.
A newer lane's coverage waits until older lanes finish flushing.
Without sufficient coverage, `engineeringDefaults.speech.turnWaitMs` without new finals completes pending turns.
Later finals never merge into a completed request.
Seen final IDs remain ignored for the socket's lifetime; unseen earlier speech can interrupt a reply and start a request.
Regression cases: `server/tests/asr-lane-order.test.ts` and `server/tests/silence.test.ts`.

### interfaces (T22, T23)

Expand Down
21 changes: 16 additions & 5 deletions server/src/media/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const partialSegment = (stt: { readonly provider: string; readonly model: string

/**
* Maps one provider answer to epoch samples: partials go to the client only; finals and the span they answered become evidence in one write, or not at all.
* Returns the end of the persisted span that no later answer revisits.
* Returns the end of the persisted span that no later answer from this lane revisits.
*/
const relayBatch = (
{ access, listener, start, send }: Omit<LiveSessionInput, 'resume_from_sample'>,
Expand Down Expand Up @@ -199,8 +199,8 @@ const itemPrompt = (access: AccessScope) =>
});

/**
* The live-ASR lane of one session: at most one provider connection, anchored at the sample it
* started from. Gaps, overload and failures detach it and report the range as degraded.
* At most one live-ASR lane receives new audio, anchored at its first sample.
* Gaps, overload and failures detach it to flush while a new lane can receive audio.
*/
const liveAsr = ({ access, listener, start, send, speech }: Omit<LiveSessionInput, 'resume_from_sample'> & {
readonly speech: { readonly onCovered: (sample_end: number) => Effect.Effect<void>; readonly replying: () => boolean };
Expand All @@ -215,6 +215,13 @@ const liveAsr = ({ access, listener, start, send, speech }: Omit<LiveSessionInpu
let lane: Lane | null = null;
let retryAt = 0;
let providerDown = false;
// A newer lane cannot settle source time while an older lane still flushes.
let draining = 0;
let covered = 0;
const cover = (end: number) => Effect.suspend(() => {
covered = Math.max(covered, end);
return draining === 0 ? speech.onCovered(covered) : Effect.void;
});
const { degrade, answered } = asrHealth(send);
const prompt = yield* itemPrompt(access);

Expand All @@ -234,7 +241,11 @@ const liveAsr = ({ access, listener, start, send, speech }: Omit<LiveSessionInpu
if (lane === null) return;
const current = lane;
lane = null;
yield* Effect.forkDaemon(closeLane(current, reason));
draining++;
yield* Effect.forkDaemon(closeLane(current, reason).pipe(
Effect.ensuring(Effect.sync(() => { draining--; })),
Effect.zipRight(Effect.suspend(() => cover(covered))),
));
});

const providerUnavailable = (from_sample: number, message: string) =>
Expand Down Expand Up @@ -268,7 +279,7 @@ const liveAsr = ({ access, listener, start, send, speech }: Omit<LiveSessionInpu
current.consumer = yield* opened.right.results.pipe(
Stream.runForEach(batch =>
Effect.zipRight(answered(current.anchor + Math.round(batch.start_s * rate)), relayBatch({ access, listener, start, send }, stt, current, batch)).pipe(
Effect.flatMap(end => (end === null ? Effect.void : speech.onCovered(end))),
Effect.flatMap(end => (end === null ? Effect.void : cover(end))),
),
),
Effect.catchAll(error =>
Expand Down
76 changes: 48 additions & 28 deletions server/src/media/speech-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,16 +115,12 @@ const sentences = <E>(text: Stream.Stream<string, E>) =>
});

/**
* What one heard segment means: empty text, Sanctum's own echo and a late transcript of the
* request that opened the window are ignored; anything else a person says over an open
* response interrupts it.
* Empty text and Sanctum's own echo are ignored. Previously seen final IDs are filtered
* by the controller; unseen speech interrupts an open response, regardless of source order.
*/
const segmentRole = (gate: ReturnType<typeof makeSpeechGate>, listener_id: ListenerId, segment: TranscriptSegment) => {
if (segment.text.trim() === '' || gate.isEcho(listener_id, segment.text)) return 'ignore';
const active = gate.active(listener_id);
if (!active) return 'listen';
const partOfRequest = active.epoch_id === segment.source.epoch_id && segment.source.sample_start < active.sample_end;
return partOfRequest ? 'ignore' : 'interrupt';
return gate.active(listener_id) ? 'interrupt' : 'listen';
};

type SpeechMessage = SpeechChunkMessage | SpeechCancelMessage;
Expand Down Expand Up @@ -171,12 +167,26 @@ const speak = (
if (expired && message) yield* io.send(message);
}).pipe(Effect.catchAll(error => Effect.logWarning('Requested speech failed', error.message)));

const startsSeparateTurn = (
turn: Pick<TranscriptSegment['source'], 'epoch_id' | 'sample_start' | 'sample_end'>,
source: TranscriptSegment['source'],
minimumGap: number,
) => turn.epoch_id !== source.epoch_id || source.sample_start - turn.sample_end >= minimumGap
|| turn.sample_start - source.sample_end >= minimumGap;
interface Turn {
readonly epoch_id: CaptureEpochId;
readonly segments: TranscriptSegment[];
sample_end: number;
}

const orderedTurns = (segments: TranscriptSegment[], minimumGap: number) => {
segments.sort((a, b) => a.source.sample_start - b.source.sample_start);
const turns: Turn[] = [];
for (const segment of segments) {
const previous = turns.at(-1);
if (previous && previous.epoch_id === segment.source.epoch_id && segment.source.sample_start - previous.sample_end < minimumGap) {
previous.segments.push(segment);
previous.sample_end = Math.max(previous.sample_end, segment.source.sample_end);
} else {
turns.push({ epoch_id: segment.source.epoch_id, sample_end: segment.source.sample_end, segments: [segment] });
}
}
return turns;
};

/**
* Per-socket speech ownership for media's session: feed every transcript segment and the
Expand All @@ -194,7 +204,7 @@ export const speechController = (options: {
const synthesizer = yield* SpeechSynthesizer;
const { listener_id, send, requestWork = () => Effect.succeed(false) } = options;
const endOfTurnSamples = (engineeringDefaults.speech.endOfTurnMs * options.sample_rate) / 1000;
let turn: { epoch_id: CaptureEpochId; segments: TranscriptSegment[]; sample_start: number; sample_end: number } | null = null;
let turn: Turn | null = null;
const seenFinals = new Set<TranscriptSegment['id']>();
let turnTimer: Fiber.Fiber<void> = Fiber.void;
let speaking: Fiber.Fiber<void> = Fiber.void;
Expand All @@ -206,13 +216,10 @@ export const speechController = (options: {
if (message) yield* send(message);
});

const completeTurn = Effect.gen(function* () {
const finished = turn;
turn = null;
if (!finished) return;
finished.segments.sort((a, b) => a.source.sample_start - b.source.sample_start);
const startReply = (finished: Turn) => Effect.gen(function* () {
const request = directRequest(finished.segments.map(segment => segment.text).join(' '));
if (request === null) return;
yield* cancel('barge_in');
const window = gate.openRequest({ listener_id, epoch_id: finished.epoch_id, request_id: finished.segments[0]!.id, sample_end: finished.sample_end });
// The work decision runs in its own daemon fiber so barge-in, which interrupts `speaking`, never aborts an enqueue.
const work = yield* Effect.forkDaemon(requestWork(request, window));
Expand All @@ -221,20 +228,33 @@ export const speechController = (options: {
started => speak({ gate, synthesizer, listener_id, send, reply: started ? Stream.make(WORK_ACKNOWLEDGEMENT) : options.respond(request) }, window)));
});

/** Extends the open turn, or completes it first when this segment starts after a pause or in a new epoch. */
const completeTurn = (covered = Infinity) => Effect.gen(function* () {
const finished = turn;
if (!finished) return;
const pending = orderedTurns(finished.segments, endOfTurnSamples);
const lastReady = pending.findLastIndex(group => covered - group.sample_end >= endOfTurnSamples);
if (lastReady < 0) return;
const ready = pending.splice(0, lastReady + 1);
turn = pending.length === 0 ? null : {
epoch_id: finished.epoch_id, sample_end: pending.at(-1)!.sample_end,
segments: pending.flatMap(group => group.segments),
};
yield* Effect.forEach(ready, startReply, { discard: true });
});

/** Collects finals before source-gap boundaries; delayed lanes can fill apparent gaps. */
const extendTurn = (segment: TranscriptSegment) =>
Effect.gen(function* () {
const { epoch_id, sample_start, sample_end } = segment.source;
if (turn && startsSeparateTurn(turn, segment.source, endOfTurnSamples)) yield* completeTurn;
const { epoch_id, sample_end } = segment.source;
if (turn && turn.epoch_id !== epoch_id) yield* completeTurn();
if (turn) {
turn.segments.push(segment);
turn.sample_start = Math.min(turn.sample_start, sample_start);
turn.sample_end = Math.max(turn.sample_end, sample_end);
} else {
turn = { epoch_id, segments: [segment], sample_start, sample_end };
turn = { epoch_id, segments: [segment], sample_end };
}
yield* Fiber.interrupt(turnTimer);
turnTimer = yield* Effect.forkDaemon(Effect.delay(completeTurn, engineeringDefaults.speech.turnWaitMs));
turnTimer = yield* Effect.forkDaemon(Effect.delay(completeTurn(), engineeringDefaults.speech.turnWaitMs));
});

return {
Expand All @@ -250,10 +270,10 @@ export const speechController = (options: {
if (segment.status === 'final') yield* extendTurn(segment);
}),
/**
* Live speech-to-text answered the audio up to `sample_end`, and no later answer revisits it: a turn that ended `endOfTurnMs`
* before it is complete now, without the `turnWaitMs` wait. Its timer then finds no turn, and a newer turn's first segment replaces that timer.
* Complete each turn whose following pause is covered, retaining later unfinished speech.
* The idle timer remains the fallback when no provider coverage proves the pause.
*/
onCovered: (sample_end: number) => (turn && sample_end - turn.sample_end >= endOfTurnSamples ? completeTurn : Effect.void),
onCovered: (sample_end: number) => completeTurn(sample_end),
/** A reply window is open, so a person speaking now interrupts it. */
replying: () => gate.active(listener_id) !== undefined,
/** Pause or disconnect: stop speech now; a reconnect never resumes it. */
Expand Down
65 changes: 65 additions & 0 deletions server/tests/asr-lane-order.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { expect, layer } from '@effect/vitest';
import { ListenerId, type ServerControlMessage, StartMessage } from '@sanctum/contracts';
import { Deferred, Effect, Layer, Schema, Stream } from 'effect';
import { liveLimits, openLiveSession } from '../src/media/session.ts';
import { makeSpeechGate, SpeechGate, SpeechReplies, SpeechWorkRequests } from '../src/media/speech-gate.ts';
import { SpeechSynthesizer } from '../src/providers/speech.ts';
import { SpeechToText } from '../src/providers/whisper.ts';
import { seedEpoch, seedListener } from './support/capture.ts';
import { eventually, fakeSpeech, MigratedDatabase, pcmFrame, seedDevice, startMessage } from './support/media.ts';

layer(MigratedDatabase)('rotated ASR lanes', it => {
it.scoped('orders delayed old-lane finals before completing a direct request and still cancels speech', () =>
Effect.gen(function* () {
const access = yield* seedDevice('Lane ordering');
const listener = yield* seedListener(access);
const listener_id = ListenerId.make(listener.listener_id);
const epoch_id = yield* seedEpoch(listener);
const release = yield* Deferred.make<void>();
const speech = fakeSpeech();
const provider = yield* Effect.provide(SpeechToText, speech.layer);
let opened = 0;
const messages: ServerControlMessage[] = [];
const requests: string[] = [];
const work: string[] = [];
const oldRetry = liveLimits.providerRetryMs;
liveLimits.providerRetryMs = 0;
yield* Effect.addFinalizer(() => Effect.sync(() => { liveLimits.providerRetryMs = oldRetry; }));
const session = yield* openLiveSession({
access, listener: { id: listener_id, capture_group_id: null }, resume_from_sample: 0,
start: Schema.decodeUnknownSync(StartMessage)(JSON.parse(startMessage({ listener_id, epoch_id, lease_generation: 1 }))),
send: message => Effect.sync(() => { messages.push(message); }),
}).pipe(Effect.provide(Layer.mergeAll(
Layer.succeed(SpeechToText, { ...provider, openStream: (...args) => provider.openStream(...args).pipe(
Effect.map(stream => opened++ === 0 ? { ...stream, finish: Effect.zipRight(Deferred.await(release), stream.finish) } : stream)),
}),
Layer.succeed(SpeechGate, makeSpeechGate()),
Layer.succeed(SpeechReplies, () => request => { requests.push(request); return Stream.never; }),
Layer.succeed(SpeechWorkRequests, () => request => Effect.sync(() => { work.push(request); return false; })),
Layer.succeed(SpeechSynthesizer, { synthesize: () => Stream.empty }),
)));
for (let i = 0; i < 40; i++) yield* session.frame(pcmFrame(i, i * 1_600));
const old = speech.streams[0]!;
old.emit({ start_s: 0, end_s: 1.5, is_final: true, text: 'Sanctum, please', confidence: 1, speaker: null });
yield* eventually(Effect.sync(() => messages.filter(message => message._tag === 'transcript').length), count => count === 1);
old.pending.push({ start_s: 1.5, end_s: 4, is_final: true, text: 'send', confidence: 1, speaker: null });
old.backlog = liveLimits.asrBacklogMs * 16 * 2;
for (let i = 40; i < 60; i++) yield* session.frame(pcmFrame(i, i * 1_600));
speech.streams[1]!.emitBatch({ start_s: 0, end_s: 2, results: [
{ start_s: 0, end_s: 1, is_final: true, text: 'the notes', confidence: 1, speaker: null },
] });
yield* eventually(Effect.sync(() => messages.filter(message => message._tag === 'transcript').length), count => count === 2);
expect(work).toEqual([]);
yield* Deferred.succeed(release, undefined);
yield* eventually(Effect.sync(() => requests), values => values.length === 1);
expect(requests).toEqual(['please send the notes']);
expect(work).toEqual(requests);
yield* session.frame(pcmFrame(60, 60 * 1_600));
speech.streams[1]!.emit({ start_s: 2, end_s: 2.1, is_final: false, text: 'wait', confidence: 1, speaker: null });
yield* eventually(Effect.sync(() => messages.filter(message => message._tag === 'speech_cancel')), values => values.length === 1);
expect(messages.find(message => message._tag === 'speech_cancel')).toMatchObject({ reason: 'barge_in' });
yield* session.stop('pause');
expect(work).toEqual(['please send the notes']);
}),
);
});
Loading
Loading