Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): bound first sends to the receive window

Dash321fe569db1d
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 3f38a39988..bf03a844ea 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -2766,7 +2766,9 @@ describe('DeviceLinkClient', () => {
(env) => env.kind === 'push' && parseTransportPayload(env.payload) !== null,
);
let meta = parseTransportPayload(pushFrames().at(-1)!.payload)!.meta;
- expect(meta.seq).toBe(MAX_TRANSPORT_PENDING_MESSAGES + 1);
+ // Prefix eviction immediately admits the next unsent message in the
+ // receive window, while the new tail stays in bounded local pending.
+ expect(meta.seq).toBe(17);
expect(meta.baseSeq).toBe(2);
// 连续洪峰:每条新 push 轮换掉一条最旧帧,队列保持满员而不再抛背压
@@ -2774,7 +2776,7 @@ describe('DeviceLinkClient', () => {
h.client.sendPush('dev-b', 'maker:event', { text: 'newest-2' }),
).not.toThrow();
meta = parseTransportPayload(pushFrames().at(-1)!.payload)!.meta;
- expect(meta.seq).toBe(MAX_TRANSPORT_PENDING_MESSAGES + 2);
+ expect(meta.seq).toBe(18);
expect(meta.baseSeq).toBe(3);
h.client.stop();
});
@@ -3324,17 +3326,26 @@ describe('DeviceLinkClient', () => {
expect(() =>
h.client.sendInvokeResult('dev-b', 'queued-result', { ok: true, result: [] }),
).not.toThrow();
- const resultFrame = h.current().sent.find(
+ expect(h.current().sent.find(
(env) => env.kind === 'invoke-result' && env.id === 'queued-result',
- )!;
- const meta = parseTransportPayload(resultFrame.payload)!.meta;
- expect(meta.seq).toBe(MAX_TRANSPORT_PENDING_MESSAGES + 1);
- expect(meta.baseSeq).toBe(2);
+ )).toBeUndefined();
// 再次满员且队头已是 live invoke:前缀为空,维持 BACKPRESSURE,不死循环不死锁
expect(() => h.client.sendInvokeResult('dev-b', 'r2', { ok: true, result: [] })).toThrow(
expect.objectContaining({ code: 'BACKPRESSURE' }),
);
+ // Drain the admitted prefixes; the queued result must eventually emerge
+ // without waiting for a retry timer or crossing the live invoke.
+ for (let i = 0; i < 8; i++) {
+ const last = h.current().sent.filter(e => parseTransportPayload(e.payload)).at(-1)!;
+ const meta = parseTransportPayload(last.payload)!.meta;
+ h.current().push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: { streamId: meta.streamId, ackSeq: meta.seq },
+ } });
+ }
+ const resultFrame = h.current().sent.find(e => e.id === 'queued-result')!;
+ expect(parseTransportPayload(resultFrame.payload)!.meta.seq).toBe(MAX_TRANSPORT_PENDING_MESSAGES + 1);
h.client.stop();
});
@@ -6914,6 +6925,69 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {
}
}
+ it('holds a large future response locally until ACK frees receive slots, then sends without the 30s retry wait', async () => {
+ await withFakeTimers(async (h, advance) => {
+ const ws = h.current();
+ for (let i = 0; i < 16; i++) {
+ h.client.sendInvokeResult('dev-b', `before-${i}`, { ok: true, result: i });
+ }
+ // This was previously sent into a full receiver and all three chunks
+ // could be rejected, even though the business timeout is only 12s.
+ h.client.sendInvokeResult('dev-b', 'large-future', { ok: true, result: 'x'.repeat(322_115) });
+ h.client.sendInvokeResult('dev-b', 'after-large', { ok: true, result: 'latest' });
+ expect(ws.sent.filter(e => e.id === 'large-future')).toHaveLength(0);
+ expect(ws.sent.filter(e => e.id === 'after-large')).toHaveLength(0);
+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(18);
+ const meta = parseTransportPayload(ws.sent.find(e => e.id === 'before-15')!.payload)!.meta;
+ await advance(100);
+ ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: { streamId: meta.streamId, ackSeq: meta.seq },
+ } });
+ expect(ws.sent.filter(e => e.id === 'large-future')).toHaveLength(3);
+ expect(ws.sent.filter(e => e.id === 'after-large')).toHaveLength(1);
+ await advance(18_000);
+ expect(ws.sent.filter(e => e.id === 'large-future')).toHaveLength(3);
+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });
+ });
+
+ it('a full receive window queues locally even with a full socket and does not block another peer', async () => {
+ await withFakeTimers(async (h, advance) => {
+ const ws = h.current();
+ const linked = establishInboundReliableLink(h, 'healthy-stream', 1, 'healthy');
+ await advance(1);
+ await linked;
+ for (let i = 0; i < 16; i++) h.client.sendInvokeResult('dev-b', `held-${i}`, { ok: true, result: null });
+ ws.bufferedAmount = MAX_TRANSPORT_WEBSOCKET_BUFFERED_BYTES;
+ expect(() => h.client.sendInvokeResult('dev-b', 'local-only', { ok: true, result: null })).not.toThrow();
+ expect(ws.sent.some(e => e.id === 'local-only')).toBe(false);
+ ws.bufferedAmount = 0;
+ h.client.sendInvokeResult('healthy', 'healthy-result', { ok: true, result: null });
+ expect(ws.sent.some(e => e.id === 'healthy-result')).toBe(true);
+ expect(h.client.isLinkReady('healthy')).toBe(true);
+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });
+ });
+
+ it('a timed-out invoke outside the receive window becomes a skip delivered when ACK advances', async () => {
+ await withFakeTimers(async (h, advance) => {
+ const ws = h.current();
+ for (let i = 0; i < 16; i++) h.client.sendInvokeResult('dev-b', `held-${i}`, { ok: true, result: null });
+ const outcome = h.client.invoke('dev-b', { channel: 'maker:list-active', args: [] }, 100)
+ .catch((error: unknown) => error);
+ await advance(101);
+ expect(await outcome).toMatchObject({ code: 'INVOKE_TIMEOUT' });
+ expect(ws.sent.some(e => e.kind === 'invoke')).toBe(false);
+ const meta = parseTransportPayload(ws.sent.find(e => e.id === 'held-15')!.payload)!.meta;
+ ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: { streamId: meta.streamId, ackSeq: meta.seq },
+ } });
+ const skip = ws.sent.find(e => e.kind === 'invoke')!;
+ expect(parseTransportPayload(skip.payload)!.meta.seq).toBe(meta.seq + 1);
+ expect(parseTransportPayload(skip.payload)!.data).toBe(JSON.stringify(makeTransportSkipPayload()));
+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });
+ });
+
it('a large response delivered after 18s is not duplicated while waiting for its first ACK', async () => {
await withFakeTimers(async (h, advance) => {
h.client.sendInvokeResult('dev-b', 'slow-page', { ok: true, result: 'x'.repeat(200 * 1024) });
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 8e2a452a95..06ba5517af 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -2709,7 +2709,11 @@ export class DeviceLinkClient {
// pending,不碰共享 ws;其它 peer 占满 send buffer 不得让它 BACKPRESSURE。
// 真会发送时仍在驱逐/腾位之前预检(旧 P1:先驱逐再拒会清空镜像历史)。
const additionalFrames = Math.max(1, frames.length);
+ const previousBaseSeq = this.getTransportBaseSeq(peer);
const willSendNow = this.isPeerSendReady(peer)
+ // Admission may evict a discardable prefix and move this message into
+ // the window. Preserve the socket preflight before that mutation.
+ && (!this.isOutsideReceiveWindow(peer, seq) || !hasPendingCapacity())
&& !this.shouldHoldRecoverySend(peer, additionalFrames)
&& (this.congestionCloseStreak === 0 || this.congestionSendBudget.canTake(
env.dst, additionalFrames, this.getReadyReliablePeers(env.dst), this.monotonicNow(),
@@ -2776,7 +2780,12 @@ export class DeviceLinkClient {
this.log.debug(`reliable transport initial send interrupted for ${env.dst.slice(0, 8)}`, err);
}
}
- if (this.isPeerSendReady(peer)) this.ensureRetryTimer(env.dst);
+ if (this.isPeerSendReady(peer)) {
+ if (this.getTransportBaseSeq(peer) !== previousBaseSeq) {
+ this.retryPending(env.dst, { ignoreInterval: false, onlyUnsent: true });
+ }
+ this.ensureRetryTimer(env.dst);
+ }
return true;
}
@@ -2785,6 +2794,7 @@ export class DeviceLinkClient {
* 一分片都没写出才抛;中途竞态只返回已上网的帧数,让恢复预算能结算部分突发。
*/
private sendReliableFrames(peer: PeerTransportState, pending: PendingReliableMessage): number {
+ if (!pending.sent && this.isOutsideReceiveWindow(peer, pending.seq)) return 0;
const frames = encodeReliableFrames(
pending.envelope,
peer.streamId,
@@ -2824,6 +2834,15 @@ export class DeviceLinkClient {
return sent;
}
+ private isOutsideReceiveWindow(peer: PeerTransportState, seq: number): boolean {
+ // Keep future messages at the sender until cumulative ACK advances. A
+ // receiver has only this many reassembly/ready slots; sending 64 pending
+ // messages into 16 slots can discard a large response, then block the stream
+ // for its entire byte-paced retry interval. Prefix eviction advances this
+ // same base, so skipped/discardable messages cannot strand the window.
+ return seq - this.getTransportBaseSeq(peer) >= MAX_TRANSPORT_REASSEMBLIES;
+ }
+
private getReadyReliablePeers(target: string): string[] {
return [...this.peerTransport.entries()]
// Include the initial target before enqueue; unacknowledged data still needs retries.
@@ -3444,6 +3463,10 @@ export class DeviceLinkClient {
peer.recoveryNeedsAck = false;
peer.recoveryFramesSent = 0;
this.retryPending(src, { ignoreInterval: true });
+ } else {
+ // Release locally queued first sends promptly, without replaying already
+ // in-flight large responses every time a partial ACK arrives.
+ this.retryPending(src, { ignoreInterval: false, onlyUnsent: true });
}
if (peer.pending.size === 0 && peer.retryTimer) {
clearInterval(peer.retryTimer);
@@ -3629,7 +3652,7 @@ export class DeviceLinkClient {
*/
private retryPending(
dst: string,
- opts: { ignoreInterval: boolean },
+ opts: { ignoreInterval: boolean; onlyUnsent?: boolean },
): void {
const peer = this.peerTransport.get(dst);
if (
@@ -3665,6 +3688,7 @@ export class DeviceLinkClient {
let framesSpent = 0;
const head = peer.pending.values().next().value;
for (const pending of peer.pending.values()) {
+ if (opts.onlyUnsent && pending.sent) continue;
// Cumulative ACK cannot confirm a tail while a byte-paced head is still
// missing. Allow one early tail retry to fill the receiver's buffer, but
// do not burn its whole retry budget (and reset this healthy slow link)
@@ -3690,7 +3714,7 @@ export class DeviceLinkClient {
sizeIntervals,
Math.min(4, 2 ** Math.max(0, pending.attempts - 1)),
);
- if (!opts.ignoreInterval && now - pending.lastSentAt < retryDelayMs) {
+ if (pending.sent && !opts.ignoreInterval && now - pending.lastSentAt < retryDelayMs) {
// A large head frame may still be inside its byte-based cooldown while
// a later small request is already eligible. Cumulative ACK cannot
// advance past the head, but one early retry lets the receiver buffer
@@ -3709,7 +3733,15 @@ export class DeviceLinkClient {
if (framesSpent > 0 && framesSpent + this.estimateReliableFrameCount(pending) > budget) break;
let sentFrames = 0;
try {
+ const previousAttempts = pending.attempts;
+ const sinceSendMs = now - pending.lastSentAt;
sentFrames = this.sendReliableFrames(peer, pending);
+ if (sentFrames > 0 && pending === head && previousAttempts > 0 && pending.bytes > RELIABLE_RETRY_BYTES_PER_INTERVAL) {
+ this.log.debug(`reliable head retry dst=${dst.slice(0, 8)} seq=${pending.seq}`
+ + ` request=${pending.envelope.id?.slice(0, 8) ?? 'none'} bytes=${pending.bytes}`
+ + ` attempts=${previousAttempts} sinceSendMs=${sinceSendMs} frames=${sentFrames}`
+ + ` pending=${peer.pending.size} ack=${peer.highestAckSeq}`);
+ }
} catch (err) {
this.log.debug(`reliable transport retry failed for ${dst.slice(0, 8)}`, err);
break;