Skip to content

Commit 55816c4

Browse files
authored
fix(slack): explicitly chunk native-data fallbacks (#117809)
* fix(slack): explicitly chunk native-data fallbacks * fix(slack): honor one-character fallback chunks * qa(slack): reconstruct chunked fallback evidence * fix(slack): cap receipt-tracked fallbacks at 4k
1 parent ef22652 commit 55816c4

8 files changed

Lines changed: 436 additions & 124 deletions

File tree

‎extensions/qa-lab/src/live-transports/slack/slack-live.observations.ts‎

Lines changed: 79 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,41 @@ export async function waitForSlackStoredMessage(params: {
284284
throw new Error(`timed out after ${params.timeoutMs}ms waiting for Slack ${params.description}`);
285285
}
286286

287+
async function waitForSlackStoredMessages(params: {
288+
channelId: string;
289+
client: WebClient;
290+
description: string;
291+
messageIds: readonly string[];
292+
oldestTs: string;
293+
sutIdentity: SlackAuthIdentity;
294+
timeoutMs: number;
295+
}) {
296+
const startedAt = Date.now();
297+
while (true) {
298+
const messages = await listSlackMessages({
299+
channelId: params.channelId,
300+
client: params.client,
301+
oldestTs: params.oldestTs,
302+
});
303+
const messagesById = new Map(
304+
messages
305+
.filter((message) => message.ts && isSutSlackMessage(message, params.sutIdentity))
306+
.map((message) => [message.ts as string, message]),
307+
);
308+
if (params.messageIds.every((messageId) => messagesById.has(messageId))) {
309+
return params.messageIds.map((messageId) => messagesById.get(messageId) as SlackMessage);
310+
}
311+
const remainingMs = params.timeoutMs - (Date.now() - startedAt);
312+
if (remainingMs <= 0) {
313+
break;
314+
}
315+
await new Promise((resolve) => {
316+
setTimeout(resolve, Math.min(1_000, remainingMs));
317+
});
318+
}
319+
throw new Error(`timed out after ${params.timeoutMs}ms waiting for Slack ${params.description}`);
320+
}
321+
287322
export function isExpectedSlackNativeTableMessage(
288323
message: SlackMessage,
289324
expectedAccessibleText: string,
@@ -337,25 +372,43 @@ export async function runSlackTableInvalidBlocksFallbackScenario(
337372
nativeDataFallbackBaseText: probe.summaryText,
338373
});
339374
} catch {
340-
const [nativeAttempt, fallbackAttempt] = instrumentation.attempts;
375+
const [nativeAttempt, ...fallbackAttempts] = instrumentation.attempts;
341376
if (nativeAttempt?.failureCode !== "invalid_blocks") {
342377
throw new Error(
343378
`expected first Slack API failure code invalid_blocks; observed ${nativeAttempt?.failureCode ?? "none"}`,
344379
);
345380
}
381+
const failedPartIndex = fallbackAttempts.findIndex((attempt) => attempt.status === "failed");
382+
const failedAttempt = failedPartIndex >= 0 ? fallbackAttempts[failedPartIndex] : undefined;
383+
const failedPart = failedPartIndex >= 0 ? String(failedPartIndex + 1) : "unknown";
346384
throw new Error(
347-
`Slack fallback failed after invalid_blocks; observed ${fallbackAttempt?.failureCode ?? "no fallback API failure code"}`,
385+
`Slack fallback part ${failedPart} failed after invalid_blocks; observed ${failedAttempt?.failureCode ?? "no fallback API failure code"}`,
348386
);
349387
}
350388
} finally {
351389
instrumentation.restore();
352390
context.sutWriteClient.chat.postMessage = originalPostMessage;
353391
}
354392

355-
const [nativeAttempt, fallbackAttempt] = instrumentation.attempts;
356-
if (instrumentation.attempts.length !== 2) {
393+
const [nativeAttempt, ...fallbackAttempts] = instrumentation.attempts;
394+
const receiptMessageIds = sent.receipt.platformMessageIds;
395+
if (receiptMessageIds.length < 2) {
357396
throw new Error(
358-
`expected exactly two Slack API attempts; observed ${instrumentation.attempts.length}`,
397+
"Slack oversized fallback receipt did not retain multiple platform message IDs",
398+
);
399+
}
400+
if (new Set(receiptMessageIds).size !== receiptMessageIds.length) {
401+
throw new Error("Slack fallback receipt retained duplicate platform message IDs");
402+
}
403+
if (
404+
sent.receipt.primaryPlatformMessageId !== receiptMessageIds[0] ||
405+
sent.messageId !== receiptMessageIds.at(-1)
406+
) {
407+
throw new Error("Slack fallback receipt did not preserve first-primary and final-message IDs");
408+
}
409+
if (instrumentation.attempts.length !== receiptMessageIds.length + 1) {
410+
throw new Error(
411+
`expected one rejected native attempt plus ${receiptMessageIds.length} fallback receipt parts; observed ${instrumentation.attempts.length} Slack API attempts`,
359412
);
360413
}
361414
if (
@@ -368,31 +421,35 @@ export async function runSlackTableInvalidBlocksFallbackScenario(
368421
);
369422
}
370423
if (
371-
fallbackAttempt?.status !== "sent" ||
372-
fallbackAttempt.nativeDataBlockCount !== 0 ||
373-
!fallbackAttempt.formattingDisabled
424+
fallbackAttempts.some(
425+
(attempt) =>
426+
attempt.status !== "sent" ||
427+
attempt.nativeDataBlockCount !== 0 ||
428+
!attempt.formattingDisabled,
429+
)
374430
) {
375-
throw new Error("Slack fallback did not use one formatting-disabled blockless API request");
431+
throw new Error("Slack fallback did not use formatting-disabled blockless API requests");
376432
}
377-
if (fallbackAttempt.text !== probe.fallbackText) {
433+
const attemptedFallbackText = fallbackAttempts.map((attempt) => attempt.text).join("");
434+
if (attemptedFallbackText !== probe.fallbackText) {
378435
throw new Error(
379-
`Slack fallback API request was incomplete: expected ${probe.fallbackText.length} characters, observed ${describeSlackObservedText(fallbackAttempt.text)}`,
436+
`Slack fallback API requests were incomplete: expected ${probe.fallbackText.length} characters, observed ${describeSlackObservedText(attemptedFallbackText)}`,
380437
);
381438
}
382439

383-
const message = await waitForSlackStoredMessage({
440+
const messages = await waitForSlackStoredMessages({
384441
channelId: context.channelId,
385442
client: context.sutReadClient,
386-
description: "stored invalid_blocks fallback message",
387-
matchesMessage: (candidate) => candidate.ts === sent.messageId,
443+
description: "stored invalid_blocks fallback messages",
444+
messageIds: receiptMessageIds,
388445
oldestTs,
389446
sutIdentity: context.sutIdentity,
390447
timeoutMs: context.timeoutMs,
391448
});
392-
const storedText = message.text ?? "";
393-
if (countSlackNativeDataBlocks(message.blocks) !== 0) {
449+
if (messages.some((message) => countSlackNativeDataBlocks(message.blocks) !== 0)) {
394450
throw new Error("stored Slack fallback retained a native data block");
395451
}
452+
const storedText = messages.map((message) => message.text ?? "").join("");
396453
const normalizedStoredText = normalizeSlackAccessibleText(storedText);
397454
if (!normalizedStoredText.includes(normalizeSlackAccessibleText(probe.firstRowText))) {
398455
throw new Error(
@@ -409,11 +466,16 @@ export async function runSlackTableInvalidBlocksFallbackScenario(
409466
`stored Slack fallback was incomplete: expected ${probe.fallbackText.length} characters, observed ${describeSlackObservedText(storedText)}`,
410467
);
411468
}
469+
const message = messages.at(-1);
470+
if (!message) {
471+
throw new Error("Slack fallback receipt had no stored message");
472+
}
412473
return {
413474
details: [
414475
"direct transport",
415476
"first API failure=invalid_blocks",
416-
"API attempts=2",
477+
`API attempts=${instrumentation.attempts.length}`,
478+
`fallback chunks=${receiptMessageIds.length}`,
417479
`data rows=${probe.dataRowCount}`,
418480
"fallback formatting disabled=true",
419481
"stored native data blocks=0",

‎extensions/qa-lab/src/live-transports/slack/slack-live.runtime.test.ts‎

Lines changed: 90 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1186,27 +1186,21 @@ describe("Slack live QA runtime helpers", () => {
11861186
expect(probe.fallbackText.split("\n")).toContain(probe.finalRowText);
11871187
});
11881188

1189-
it("proves the public Slack send path stores one complete formatting-disabled fallback", async () => {
1189+
it("proves the public Slack send path stores complete ordered fallback chunks", async () => {
11901190
const probe = testing.buildSlackInvalidBlocksTableProbe();
1191-
let storedPayload: Record<string, unknown> | undefined;
1191+
const storedPayloads: Array<Record<string, unknown> & { ts: string }> = [];
11921192
const postMessage = vi.fn(async (payload: Record<string, unknown>) => {
1193-
storedPayload = payload;
1194-
return { channel: "C123456789", ok: true, ts: "2.000000" };
1193+
const ts = `2.${String(storedPayloads.length + 1).padStart(6, "0")}`;
1194+
storedPayloads.push({ ...payload, ts });
1195+
return { channel: "C123456789", ok: true, ts };
11951196
});
11961197
const history = vi.fn(async () => ({
1197-
messages: storedPayload
1198-
? [
1199-
{
1200-
blocks: storedPayload.blocks,
1201-
text:
1202-
typeof storedPayload.text === "string"
1203-
? storedPayload.text.replace(/\s+/gu, " ")
1204-
: storedPayload.text,
1205-
ts: "2.000000",
1206-
user: "U999999999",
1207-
},
1208-
]
1209-
: [],
1198+
messages: storedPayloads.toReversed().map((payload) => ({
1199+
blocks: payload.blocks,
1200+
text: typeof payload.text === "string" ? payload.text.replace(/\s+/gu, " ") : payload.text,
1201+
ts: payload.ts,
1202+
user: "U999999999",
1203+
})),
12101204
}));
12111205
const sutWriteClient = { chat: { postMessage } };
12121206
const cfg = testing.buildSlackQaConfig(
@@ -1230,28 +1224,48 @@ describe("Slack live QA runtime helpers", () => {
12301224
timeoutMs: 0,
12311225
});
12321226

1233-
expect(postMessage).toHaveBeenCalledTimes(1);
1234-
const [fallbackRequest] = postMessage.mock.calls[0] ?? [];
1235-
expect(fallbackRequest).not.toHaveProperty("blocks");
1236-
expect(fallbackRequest).toMatchObject({ mrkdwn: false });
1237-
const fallbackText = typeof fallbackRequest?.text === "string" ? fallbackRequest.text : "";
1227+
expect(postMessage).toHaveBeenCalledTimes(3);
1228+
const fallbackRequests = postMessage.mock.calls.map(([request]) => request);
1229+
expect(fallbackRequests.every((request) => !Object.hasOwn(request, "blocks"))).toBe(true);
1230+
expect(fallbackRequests.every((request) => request.mrkdwn === false)).toBe(true);
1231+
const fallbackText = fallbackRequests.map((request) => request.text).join("");
1232+
expect(fallbackText).toHaveLength(probe.fallbackText.length);
12381233
expect(fallbackText.split("\n")).toContain(probe.firstRowText);
12391234
expect(fallbackText.split("\n")).toContain(probe.finalRowText);
1240-
expect(result.message).toMatchObject({ ts: "2.000000", user: "U999999999" });
1241-
expect(result.message.text).toBe(fallbackText.replace(/\s+/gu, " "));
1235+
expect(storedPayloads.map((payload) => payload.ts)).toEqual([
1236+
"2.000001",
1237+
"2.000002",
1238+
"2.000003",
1239+
]);
1240+
expect(
1241+
storedPayloads
1242+
.map((payload) =>
1243+
typeof payload.text === "string" ? payload.text.replace(/\s+/gu, " ") : "",
1244+
)
1245+
.join(""),
1246+
).toBe(fallbackText.replace(/\s+/gu, " "));
1247+
expect(result.message).toMatchObject({ ts: "2.000003", user: "U999999999" });
12421248
expect(result.details).toContain("first API failure=invalid_blocks");
1249+
expect(result.details).toContain("API attempts=4");
12431250
expect(result.details).toContain("fallback formatting disabled=true");
1251+
expect(result.details).toContain("fallback chunks=3");
1252+
expect(result.details).toContain("first row=present");
1253+
expect(result.details).toContain("final row=present");
12441254
expect(result.details).toContain("complete delivery=true");
12451255
expect(sutWriteClient.chat.postMessage).toBe(postMessage);
12461256
});
12471257

12481258
it("bounds invalid_blocks readback diagnostics while showing the observed text", async () => {
12491259
const malformedReadback = `BROKEN-${"x".repeat(2_000)}`;
1250-
const postMessage = vi.fn(async () => ({
1251-
channel: "C123456789",
1252-
ok: true,
1253-
ts: "2.000000",
1254-
}));
1260+
let postCount = 0;
1261+
const postMessage = vi.fn(async () => {
1262+
postCount += 1;
1263+
return {
1264+
channel: "C123456789",
1265+
ok: true,
1266+
ts: `2.${String(postCount).padStart(6, "0")}`,
1267+
};
1268+
});
12551269
const sutWriteClient = { chat: { postMessage } };
12561270
const cfg = testing.buildSlackQaConfig(
12571271
{},
@@ -1273,7 +1287,11 @@ describe("Slack live QA runtime helpers", () => {
12731287
sutReadClient: {
12741288
conversations: {
12751289
history: vi.fn(async () => ({
1276-
messages: [{ text: malformedReadback, ts: "2.000000", user: "U999999999" }],
1290+
messages: [
1291+
{ text: "", ts: "2.000003", user: "U999999999" },
1292+
{ text: "", ts: "2.000002", user: "U999999999" },
1293+
{ text: malformedReadback, ts: "2.000001", user: "U999999999" },
1294+
],
12771295
})),
12781296
},
12791297
} as never,
@@ -1318,7 +1336,9 @@ describe("Slack live QA runtime helpers", () => {
13181336
sutWriteClient: sutWriteClient as never,
13191337
timeoutMs: 0,
13201338
}),
1321-
).rejects.toThrow("Slack fallback failed after invalid_blocks; observed invalid_arguments");
1339+
).rejects.toThrow(
1340+
"Slack fallback part 1 failed after invalid_blocks; observed invalid_arguments",
1341+
);
13221342
expect(sutWriteClient.chat.postMessage).toBe(postMessage);
13231343
});
13241344

@@ -1351,8 +1371,46 @@ describe("Slack live QA runtime helpers", () => {
13511371
timeoutMs: 0,
13521372
}),
13531373
).rejects.toThrow(
1354-
"Slack fallback failed after invalid_blocks; observed no fallback API failure code",
1374+
"Slack fallback part 1 failed after invalid_blocks; observed no fallback API failure code",
1375+
);
1376+
expect(sutWriteClient.chat.postMessage).toBe(postMessage);
1377+
});
1378+
1379+
it("reports a later Slack fallback chunk failure", async () => {
1380+
const postMessage = vi
1381+
.fn()
1382+
.mockResolvedValueOnce({ channel: "C123456789", ok: true, ts: "2.000001" })
1383+
.mockRejectedValueOnce(
1384+
Object.assign(new Error("do not persist this raw platform detail"), {
1385+
data: { error: "invalid_arguments", ok: false },
1386+
}),
1387+
);
1388+
const sutWriteClient = { chat: { postMessage } };
1389+
const cfg = testing.buildSlackQaConfig(
1390+
{},
1391+
{
1392+
channelId: "C123456789",
1393+
driverBotUserId: "U111111111",
1394+
sutAccountId: "sut",
1395+
sutAppToken: "xapp-sut",
1396+
sutBotToken: "xoxb-sut",
1397+
},
1398+
);
1399+
1400+
await expect(
1401+
testing.runSlackTableInvalidBlocksFallbackScenario({
1402+
cfg,
1403+
channelId: "C123456789",
1404+
sutAccountId: "sut",
1405+
sutIdentity: { userId: "U999999999" },
1406+
sutReadClient: { conversations: { history: vi.fn() } } as never,
1407+
sutWriteClient: sutWriteClient as never,
1408+
timeoutMs: 0,
1409+
}),
1410+
).rejects.toThrow(
1411+
"Slack fallback part 2 failed after invalid_blocks; observed invalid_arguments",
13551412
);
1413+
expect(postMessage).toHaveBeenCalledTimes(2);
13561414
expect(sutWriteClient.chat.postMessage).toBe(postMessage);
13571415
});
13581416

‎extensions/slack/src/limits.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
// Slack plugin module implements limits behavior.
22
export const SLACK_TEXT_LIMIT = 8000;
33

4+
// Slack recommends no more than 4,000 characters for chat.postMessage text.
5+
// Longer fallback posts can be split while the API returns only one timestamp.
6+
// https://api.slack.com/methods/chat.postMessage#truncating
7+
export const SLACK_MESSAGE_TEXT_RECOMMENDED_LIMIT = 4_000;
8+
49
// chat.update documents 4,000 characters but rejects text above 4,000 UTF-8 bytes in live use.
510
// https://docs.slack.dev/reference/methods/chat.update/#errors
611
export const SLACK_EDIT_TEXT_MAX_BYTES = 4_000;

0 commit comments

Comments
 (0)