fix(lambda): return invocation log tails for LogType=Tail (#8618) (#8661)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-17 05:50:15 -04:00
1 parent 7ed62b2597
commit c2401d7e06
23 files changed
+1100 -28

No files matched your search

@@ -222,6 +222,64 @@ class LambdaExecutorServiceTest {
assertNull(result.getFunctionError());
}
@Test
void requestedLogTailIsReadBeforeTheEnvironmentIsReleased() {
RuntimeApiServer runtime = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("logs", "test-fn", runtime, ContainerState.WARM);
handle.setLogTailReader(initialization -> () -> {
verify(warmPool, never()).release(handle);
return "aGVsbG8K";
});
stubInvocationResult(handle, new InvokeResult(200, "Unhandled", "{}".getBytes(), null, "logs"));
InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, 0, null, null, true);
assertEquals("aGVsbG8K", result.getLogResult());
assertEquals("Unhandled", result.getFunctionError());
verify(warmPool).release(handle);
}
@Test
void anInvocationWithoutTailDoesNotReadTheEnvironmentLogs() {
RuntimeApiServer runtime = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("no-logs", "test-fn", runtime, ContainerState.WARM);
handle.setLogTailReader(initialization -> () -> {
throw new AssertionError("Logs were not requested");
});
stubInvocationResult(handle, new InvokeResult(200, null, "{}".getBytes(), null, "no-logs"));
InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse);
assertNull(result.getLogResult());
verify(warmPool).release(handle);
}
@Test
void aLogReadFailurePreservesTheFunctionResultAndReleasesItsEnvironment() {
RuntimeApiServer runtime = mock(RuntimeApiServer.class);
ContainerHandle handle = new ContainerHandle("bad-logs", "test-fn", runtime, ContainerState.WARM);
handle.setLogTailReader(initialization -> () -> {
throw new IllegalStateException("log driver unavailable");
});
stubInvocationResult(handle, new InvokeResult(200, null, "{}".getBytes(), null, "bad-logs"));
InvokeResult result = executor.invoke(fn, "{}".getBytes(), InvocationType.RequestResponse, 0, null, null, true);
assertEquals(200, result.getStatusCode());
assertNull(result.getFunctionError());
verify(warmPool).release(handle);
verify(warmPool, never()).destroyHandle(handle);
}
private void stubInvocationResult(ContainerHandle handle, InvokeResult result) {
when(warmPool.acquire(fn)).thenReturn(handle);
doAnswer(call -> {
PendingInvocation invocation = call.getArgument(0);
invocation.getResultFuture().complete(result);
return invocation.getResultFuture();
}).when(handle.getRuntimeApiServer()).enqueue(any());
}
@Test
void dispatchWait_coldRuntimeGetsTheInitBudget() {
LambdaExecutorService withBudget =
@@ -0,0 +1,112 @@
package io.floci.aws.services.lambda;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.LambdaCodeFixtures;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.FunctionCode;
import software.amazon.awssdk.services.lambda.model.InvocationType;
import software.amazon.awssdk.services.lambda.model.InvokeResponse;
import software.amazon.awssdk.services.lambda.model.LogType;
import software.amazon.awssdk.services.lambda.model.Runtime;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class LambdaInvokeLogTailDockerIntegrationTest {
@Inject
DockerClient dockerClient;
@Test
void synchronousInvokeReturnsItsOwnLogsThroughTheSdk() {
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
"Docker is required for Lambda invocation log tails");
String name = "invoke-log-tail-" + UUID.randomUUID().toString().substring(0, 8);
try (LambdaClient client = AwsTestClients.create(LambdaClient.builder(), "000000000000", Region.US_EAST_1)) {
client.createFunction(request -> request.functionName(name)
.runtime(Runtime.NODEJS22_X).handler("index.handler")
.role("arn:aws:iam::000000000000:role/lambda-role").timeout(10)
.code(FunctionCode.builder().zipFile(SdkBytes.fromByteArray(LambdaCodeFixtures.nodeJsZip("""
console.log('initialization output');
exports.handler = async (event) => {
console.log('hello from log tail probe ' + event.marker);
console.error('stderr ' + event.marker);
if (event.large) process.stdout.write('é'.repeat(9000) + ' END ' + event.marker + '\\n');
if (event.fail) throw new Error('failure ' + event.marker);
return {ok: true};
};
"""))).build()));
try {
InvokeResponse response = client.invoke(request -> request.functionName(name)
.logType(LogType.TAIL).payload(SdkBytes.fromUtf8String("{\"marker\":\"first\"}")));
assertEquals(200, response.statusCode());
assertEquals("{\"ok\":true}", response.payload().asUtf8String());
assertNotNull(response.logResult(), "LogType=Tail must return X-Amz-Log-Result");
String logs = new String(Base64.getDecoder().decode(response.logResult()), StandardCharsets.UTF_8);
assertTrue(logs.contains("hello from log tail probe first"), logs);
assertTrue(logs.contains("initialization output"), logs);
assertTrue(logs.contains("stderr first"), logs);
InvokeResponse warm = client.invoke(request -> request.functionName(name)
.invocationType(InvocationType.REQUEST_RESPONSE).logType(LogType.TAIL)
.payload(SdkBytes.fromUtf8String("{\"marker\":\"second 世界\"}")));
String warmLogs = decoded(warm);
assertTrue(warmLogs.contains("second 世界"), warmLogs);
assertFalse(warmLogs.contains("first"), warmLogs);
assertFalse(warmLogs.contains("initialization output"), warmLogs);
InvokeResponse failed = client.invoke(request -> request.functionName(name).logType(LogType.TAIL)
.payload(SdkBytes.fromUtf8String("{\"marker\":\"failed\",\"fail\":true}")));
assertEquals("Unhandled", failed.functionError());
assertTrue(decoded(failed).contains("failure failed"), decoded(failed));
assertFalse(decoded(failed).contains("second"), decoded(failed));
InvokeResponse large = client.invoke(request -> request.functionName(name).logType(LogType.TAIL)
.payload(SdkBytes.fromUtf8String("{\"marker\":\"large\",\"large\":true}")));
byte[] largeOutput = ("é".repeat(9000) + " END large\n").getBytes(StandardCharsets.UTF_8);
byte[] actualTail = Base64.getDecoder().decode(large.logResult());
assertArrayEquals(Arrays.copyOfRange(largeOutput, largeOutput.length - 4096, largeOutput.length),
actualTail, () -> "Unexpected tail metadata: "
+ new String(actualTail, StandardCharsets.UTF_8).replace("é", ""));
InvokeResponse noTail = client.invoke(request -> request.functionName(name)
.logType(LogType.NONE).payload(SdkBytes.fromUtf8String("{}")));
assertNull(noTail.logResult());
InvokeResponse defaultLogs = client.invoke(request -> request.functionName(name)
.payload(SdkBytes.fromUtf8String("{}")));
assertNull(defaultLogs.logResult());
InvokeResponse dryRun = client.invoke(request -> request.functionName(name)
.invocationType(InvocationType.DRY_RUN).logType(LogType.TAIL));
assertEquals(204, dryRun.statusCode());
assertNull(dryRun.logResult());
} finally {
client.deleteFunction(request -> request.functionName(name));
}
}
}
private static String decoded(InvokeResponse response) {
assertNotNull(response.logResult());
return new String(Base64.getDecoder().decode(response.logResult()), StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,67 @@
package io.floci.aws.services.lambda;
import io.floci.aws.services.lambda.model.InvocationType;
import io.floci.aws.services.lambda.model.InvokeResult;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@QuarkusTest
class LambdaInvokeLogTailIntegrationTest {
@InjectMock
LambdaService lambdaService;
@ParameterizedTest
@ValueSource(strings = {"RequestResponse", "default"})
void aSynchronousTailRequestReturnsTheEncodedHeader(String invocationType) {
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any(), any(), eq(true)))
.thenReturn(result(200, "aGVsbG8K"));
given()
.header("X-Amz-Invocation-Type", "default".equals(invocationType) ? "" : invocationType)
.header("X-Amz-Log-Type", "Tail")
.body("{}")
.when()
.post("/2015-03-31/functions/log-tail/invocations")
.then()
.statusCode(200)
.header("X-Amz-Log-Result", equalTo("aGVsbG8K"));
verify(lambdaService).invoke(any(), eq("log-tail"), any(), any(),
eq(InvocationType.RequestResponse), any(), any(), any(), eq(true));
}
@ParameterizedTest
@ValueSource(strings = {"Event", "DryRun"})
void nonSynchronousInvocationsIgnoreTail(String invocationType) {
int status = "Event".equals(invocationType) ? 202 : 204;
when(lambdaService.invoke(any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(result(status, "should-not-be-exposed"));
given()
.header("X-Amz-Invocation-Type", invocationType)
.header("X-Amz-Log-Type", "Tail")
.body("{}")
.when()
.post("/2015-03-31/functions/log-tail/invocations")
.then()
.statusCode(status)
.header("X-Amz-Log-Result", nullValue());
}
private static InvokeResult result(int status, String logs) {
return new InvokeResult(status, null, "{}".getBytes(StandardCharsets.UTF_8), logs, "request-id");
}
}
@@ -0,0 +1,63 @@
package io.floci.aws.services.lambda.durable;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.concurrent.CompletableFuture;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DurableInvocationLogsTest {
@Test
void resumingAnExecutionKeepsOnlyTheLastFourKilobytesAcrossHandlers() {
DurableInvocationLogs logs = new DurableInvocationLogs();
logs.acquire();
byte[] first = "first handler\n".getBytes(StandardCharsets.UTF_8);
logs.beginInvocation();
logs.complete(Base64.getEncoder().encodeToString(first));
byte[] second = ("界".repeat(3000) + " second handler\n").getBytes(StandardCharsets.UTF_8);
logs.beginInvocation();
logs.complete(Base64.getEncoder().encodeToString(second));
assertArrayEquals(Arrays.copyOfRange(second, second.length - 4096, second.length),
Base64.getDecoder().decode(logs.snapshot().join()));
logs.release();
assertTrue(logs.unused());
}
@Test
void attachedCallersShareTheCaptureUntilTheLastHandlerAndCallerFinish() {
DurableInvocationLogs logs = new DurableInvocationLogs();
logs.acquire();
logs.acquire();
logs.beginInvocation();
CompletableFuture<String> snapshot = logs.snapshot();
logs.release();
assertFalse(logs.unused());
logs.release();
assertFalse(logs.unused(), "an in-flight handler still owns the capture");
assertFalse(snapshot.isDone());
logs.complete("aGFuZGxlcgo=");
assertArrayEquals("handler\n".getBytes(StandardCharsets.UTF_8), Base64.getDecoder().decode(snapshot.join()));
assertTrue(logs.unused());
}
@Test
void resetCancelsPendingLogWaiters() {
DurableInvocationLogs logs = new DurableInvocationLogs();
logs.beginInvocation();
CompletableFuture<String> snapshot = logs.snapshot();
logs.cancel();
assertTrue(snapshot.isCompletedExceptionally());
assertTrue(logs.unused());
}
}
@@ -20,6 +20,8 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Runs a real Python function in a container. Its FAILED envelope closes the execution and the
@@ -81,9 +83,25 @@ class LambdaDurableFunctionsDockerIntegrationTest {
.body("DurableExecutions[0].Status", equalTo("FAILED"));
}
@Test
void aSynchronousDurableTailRequestIncludesTheHandlerLogs() {
Response response = given()
.header("X-Amz-Durable-Execution-Name", "docker-fail-tail")
.header("X-Amz-Log-Type", "Tail")
.body("{\"fail\": true}")
.post(LAMBDA + "/functions/" + FUNCTION + ":1/invocations");
assertEquals(200, response.statusCode(), response.asString());
assertEquals("Unhandled", response.getHeader("X-Amz-Function-Error"));
assertNotNull(response.getHeader("X-Amz-Log-Result"), "Durable Invoke must return requested handler logs");
String logs = new String(Base64.getDecoder().decode(response.getHeader("X-Amz-Log-Result")), StandardCharsets.UTF_8);
assertTrue(logs.contains("durable handler log"), logs);
}
static String handlerSource() {
return """
def handler(event, context):
print("durable handler log", flush=True)
return {"Status": "FAILED",
"Error": {"ErrorMessage": "asked to fail", "ErrorType": "TestFailure"}}
""";
@@ -27,6 +27,7 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -46,6 +47,9 @@ class LambdaDurableProtocolIntegrationTest {
@Inject
ScriptedDurableFunctionInvoker invoker;
@Inject
DurableExecutionService executions;
@BeforeEach
void createFunctionAndDrainInvocations() {
given()
@@ -91,6 +95,33 @@ class LambdaDurableProtocolIntegrationTest {
assertEquals(200, invoke.get(30, TimeUnit.SECONDS).statusCode());
}
@Test
void aTailRequestWaitsForHandlerLogsAfterACheckpointClosesTheExecution() throws Exception {
CompletableFuture<Response> invoke = CompletableFuture.supplyAsync(() -> given()
.header("X-Amz-Durable-Execution-Name", "checkpoint-log-tail")
.header("X-Amz-Log-Type", "Tail")
.body("{}")
.post(LAMBDA + "/functions/" + FUNCTION + ":$LATEST/invocations"));
Invocation invocation = invoker.awaitInvocation(Duration.ofSeconds(30));
assertTrue(invocation.logTail());
JsonNode event = MAPPER.readTree(invocation.payload());
String arn = event.get("DurableExecutionArn").asText();
checkpoint(arn, event.get("CheckpointToken").asText(), """
{"Id": "x", "Type": "EXECUTION", "Action": "SUCCEED", "Payload": "\\"done\\""}
""");
assertTrue(executions.awaitCompletion(arn).isDone());
assertFalse(executions.invocationLogs(arn).isDone(), "the handler still owns its final log tail");
invocation.response().complete(new DurableInvocationResult("tail-request",
"{\"Status\":\"SUCCEEDED\"}".getBytes(StandardCharsets.UTF_8), null, "aGFuZGxlciBsb2dzCg=="));
Response response = invoke.get(30, TimeUnit.SECONDS);
assertEquals(200, response.statusCode());
assertEquals("\"done\"", response.asString());
assertEquals("aGFuZGxlciBsb2dzCg==", response.getHeader("X-Amz-Log-Result"));
assertEquals("", executions.invocationLogs(arn).join(), "request log capture is released after the response");
}
@Test
void aChainedInvokeTraceHeaderReachesTheChildInvocationAndExecution() throws Exception {
String traceHeader = "Root=1-6af70000-0000000000000000000000e1;Parent=00000000000000e1;Sampled=1";
@@ -21,7 +21,7 @@ import java.util.concurrent.TimeoutException;
@ApplicationScoped
public class ScriptedDurableFunctionInvoker implements DurableFunctionInvoker {
public record Invocation(ResolvedDurableTarget target, byte[] payload, String traceId,
public record Invocation(ResolvedDurableTarget target, byte[] payload, String traceId, boolean logTail,
CompletableFuture<DurableInvocationResult> response) {
}
@@ -41,7 +41,13 @@ public class ScriptedDurableFunctionInvoker implements DurableFunctionInvoker {
@Override
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
String traceId) {
Invocation invocation = new Invocation(target, payload, traceId, new CompletableFuture<>());
return invoke(target, payload, requestId, traceId, false);
}
@Override
public DurableInvocationResult invoke(ResolvedDurableTarget target, byte[] payload, String requestId,
String traceId, boolean logTail) {
Invocation invocation = new Invocation(target, payload, traceId, logTail, new CompletableFuture<>());
invocations.add(invocation);
try {
return invocation.response().get(30, TimeUnit.SECONDS);
@@ -0,0 +1,85 @@
package io.floci.aws.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.LogContainerCmd;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.floci.aws.services.lambda.model.ContainerState;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class InvocationLogTailClockSkewTest {
@ParameterizedTest
@ValueSource(strings = {"2000-01-01T00:00:00Z", "2099-01-01T00:00:00Z"})
void warmInvocationUsesTheDaemonsBoundaryEvenWhenItsClockDrifts(String sourceTime) {
Instant previous = Instant.parse(sourceTime);
String earlier = previous + " previous invocation\n";
String current = previous.plusNanos(1) + " current invocation\n";
DockerClient docker = mock(DockerClient.class);
when(docker.logContainerCmd("worker")).thenAnswer(call -> snapshotCommand(earlier, current));
ContainerHandle handle = new ContainerHandle("worker", "function", null, ContainerState.WARM);
handle.setLogTailReader(initialization -> InvocationLogTail.captureDocker(docker, "worker", initialization));
handle.beginInvocation(false);
String logs = handle.beginInvocation(true).get();
assertEquals("current invocation\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8));
}
private static LogContainerCmd snapshotCommand(String earlier, String current) {
LogContainerCmd command = mock(LogContainerCmd.class, RETURNS_SELF);
AtomicInteger lines = new AtomicInteger();
doAnswer(call -> {
lines.set(call.getArgument(0));
return command;
}).when(command).withTail(anyInt());
doAnswer(call -> {
ResultCallback<Frame> callback = call.getArgument(0);
callback.onNext(new Frame(StreamType.STDOUT, earlier.getBytes(StandardCharsets.UTF_8)));
if (lines.get() != 1) {
callback.onNext(new Frame(StreamType.STDOUT, current.getBytes(StandardCharsets.UTF_8)));
}
callback.onComplete();
return callback;
}).when(command).exec(any());
return command;
}
@Test
void eachDockerRecordDropsItsPrefixEvenWhenThePreviousRecordHasNoNewline() {
DockerClient docker = mock(DockerClient.class);
when(docker.logContainerCmd("worker")).thenAnswer(call -> snapshotCommand(
"2026-11-16T19:00:00.001Z partial ", "2026-11-16T19:00:00.002Z continuation\n"));
String logs = InvocationLogTail.readDocker(docker, "worker", Instant.EPOCH);
assertEquals("partial continuation\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8));
}
@Test
void aDockerTimestampSplitAcrossCallbacksIsReassembled() {
DockerClient docker = mock(DockerClient.class);
when(docker.logContainerCmd("worker")).thenAnswer(call -> snapshotCommand(
"2026-11-16T19:", "00:00.001Z handler output\n"));
String logs = InvocationLogTail.readDocker(docker, "worker", Instant.EPOCH);
assertEquals("handler output\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,99 @@
package io.floci.aws.services.lambda.launcher;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InvocationLogTailTest {
@Test
void emptyLogsHaveAnEmptyBase64Result() throws Exception {
assertEquals("", InvocationLogTail.read(new ByteArrayInputStream(new byte[0])));
}
@Test
void truncationCountsUtf8BytesRatherThanCharacters() throws Exception {
byte[] logs = ("earlier output\n" + "界".repeat(3000) + "\nlast line\n").getBytes(StandardCharsets.UTF_8);
byte[] actual = Base64.getDecoder().decode(InvocationLogTail.read(new ByteArrayInputStream(logs)));
assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length), actual);
}
@Test
void repeatedSmallWritesWrapWithoutLosingTheTail() {
InvocationLogTail tail = new InvocationLogTail();
byte[] logs = ("hello\n".repeat(2000) + "last\n").getBytes(StandardCharsets.UTF_8);
for (int offset = 0; offset < logs.length; offset += 17) {
tail.append(logs, offset, Math.min(17, logs.length - offset));
}
assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length),
Base64.getDecoder().decode(tail.encoded()));
}
@Test
void aSingleOversizedWriteKeepsTheLastFourKilobytes() {
InvocationLogTail tail = new InvocationLogTail();
byte[] prefix = "old".getBytes(StandardCharsets.UTF_8);
tail.append(prefix, 0, prefix.length);
byte[] logs = ("x".repeat(8000) + "end\n").getBytes(StandardCharsets.UTF_8);
tail.append(logs, 0, logs.length);
assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length),
Base64.getDecoder().decode(tail.encoded()));
}
@Test
void timestampFilteringExcludesAnEarlierInvocationInTheSameSecond() {
InvocationLogTail tail = new InvocationLogTail();
Instant start = Instant.parse("2026-11-16T19:00:00.500Z");
tail.appendTimestamped(("2026-11-16T19:00:00.499999999Z previous invocation\n"
+ "2026-11-16T19:00:00.500000000Z current stdout\n"
+ "2026-11-16T19:00:00.501000000Z current stderr\n").getBytes(StandardCharsets.UTF_8), start);
assertEquals("current stdout\ncurrent stderr\n", decoded(tail));
}
@Test
void aLogRecordSplitAcrossFramesKeepsItsContinuationAndUnterminatedTail() {
InvocationLogTail tail = new InvocationLogTail();
Instant start = Instant.parse("2026-11-16T19:00:00Z");
tail.appendTimestamped("2026-11-16T19:00:00.001Z hello ".getBytes(StandardCharsets.UTF_8), start);
tail.appendTimestamped("world\n2026-11-16T19:00:00.002Z last".getBytes(StandardCharsets.UTF_8), start);
assertEquals("hello world\nlast", decoded(tail));
}
private static String decoded(InvocationLogTail tail) {
return new String(Base64.getDecoder().decode(tail.encoded()), StandardCharsets.UTF_8);
}
@Test
void aTimestampPrefixSplitAcrossFramesIsRemovedWithoutLosingOutput() {
InvocationLogTail tail = new InvocationLogTail();
Instant start = Instant.parse("2026-11-16T19:00:00Z");
tail.appendTimestamped("2026-11-16T19:".getBytes(StandardCharsets.UTF_8), start);
tail.appendTimestamped("00:00.001Z hello\n".getBytes(StandardCharsets.UTF_8), start);
assertEquals("hello\n", decoded(tail));
}
@Test
void everySplitPointPreservesTheSameTimestampedUtf8Output() {
byte[] record = "2026-11-16T19:00:00.001Z hello 世界\n".getBytes(StandardCharsets.UTF_8);
for (int split = 1; split < record.length; split++) {
InvocationLogTail tail = new InvocationLogTail();
tail.appendTimestamped(Arrays.copyOfRange(record, 0, split), Instant.EPOCH);
tail.appendTimestamped(Arrays.copyOfRange(record, split, record.length), Instant.EPOCH);
assertEquals("hello 世界\n", decoded(tail), "split at byte " + split);
}
}
}
@@ -0,0 +1,109 @@
package io.floci.aws.services.lambda.launcher.kubernetes;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class KubernetesInvocationLogTailTest {
@Test
void invocationLogsUseABoundedNonFollowingSnapshotAndLeaveStreamingAvailable() throws Exception {
AtomicReference<URI> requested = new AtomicReference<>();
byte[] logs = ("界".repeat(3000) + "\nlast line\n").getBytes(StandardCharsets.UTF_8);
byte[] timestamped = ("2026-11-16T19:00:00.123456790Z " + "界".repeat(3000)
+ "\n2026-11-16T19:00:00.123456791Z last line\n").getBytes(StandardCharsets.UTF_8);
HttpServer server = serveLogs(uri -> uri.getRawQuery().contains("timestamps=true") ? timestamped : logs, requested);
try (HttpClient http = HttpClient.newHttpClient()) {
KubernetesApiClient client = new KubernetesApiClient(
URI.create("http://127.0.0.1:" + server.getAddress().getPort()), http, () -> "test-token");
Instant since = Instant.parse("2026-11-16T19:00:00.123456789Z");
byte[] tail = Base64.getDecoder().decode(client.readPodLogTail("functions", "worker", since));
assertArrayEquals(Arrays.copyOfRange(logs, logs.length - 4096, logs.length), tail);
assertEquals("/api/v1/namespaces/functions/pods/worker/log", requested.get().getPath());
String query = URLDecoder.decode(requested.get().getRawQuery(), StandardCharsets.UTF_8);
assertTrue(query.contains("container=runtime"), query);
assertTrue(query.contains("follow=false"), query);
assertTrue(query.contains("tailLines=4096"), query);
assertTrue(query.contains("timestamps=true"), query);
assertTrue(query.contains("sinceTime=2026-11-16T19:00:00Z"), query);
try (InputStream stream = client.openPodLogStream("functions", "worker", "runtime")) {
assertArrayEquals(logs, stream.readAllBytes());
}
assertEquals("container=runtime&follow=true", requested.get().getRawQuery());
} finally {
server.stop(0);
}
}
@Test
void clientFilteringRemovesEarlierRecordsWithinTheSameSecond() throws Exception {
byte[] logs = ("2026-11-16T19:00:00.123456788Z previous invocation\n"
+ "2026-11-16T19:00:00.123456789Z current invocation\n").getBytes(StandardCharsets.UTF_8);
HttpServer server = serveLogs(uri -> logs, new AtomicReference<>());
try (HttpClient http = HttpClient.newHttpClient()) {
KubernetesApiClient client = new KubernetesApiClient(
URI.create("http://127.0.0.1:" + server.getAddress().getPort()), http, () -> "test-token");
String tail = client.readPodLogTail("functions", "worker", Instant.parse("2026-11-16T19:00:00.123456789Z"));
assertEquals("current invocation\n", new String(Base64.getDecoder().decode(tail), StandardCharsets.UTF_8));
} finally {
server.stop(0);
}
}
@ParameterizedTest
@ValueSource(strings = {"2000-01-01T00:00:00Z", "2099-01-01T00:00:00Z"})
void warmInvocationUsesTheKubeletsClock(String sourceTime) throws Exception {
Instant previous = Instant.parse(sourceTime);
String earlier = previous + " previous invocation\n";
String current = previous.plusNanos(1) + " current invocation\n";
HttpServer server = serveLogs(uri -> (uri.getRawQuery().contains("tailLines=1&")
? earlier : earlier + current).getBytes(StandardCharsets.UTF_8), new AtomicReference<>());
try (HttpClient http = HttpClient.newHttpClient()) {
KubernetesApiClient client = new KubernetesApiClient(
URI.create("http://127.0.0.1:" + server.getAddress().getPort()), http, () -> "test-token");
String logs = client.capturePodLogTail("functions", "worker", false).get();
assertEquals("current invocation\n", new String(Base64.getDecoder().decode(logs), StandardCharsets.UTF_8));
} finally {
server.stop(0);
}
}
private static HttpServer serveLogs(Function<URI, byte[]> response, AtomicReference<URI> requested) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
requested.set(exchange.getRequestURI());
byte[] logs = response.apply(exchange.getRequestURI());
exchange.sendResponseHeaders(200, logs.length);
try (exchange) {
exchange.getResponseBody().write(logs);
}
});
server.start();
return server;
}
}