feat(cloudwatch): add Logs Insights query support (#1448)

* feat(cloudwatch): add Logs Insights query support

Implement StartQuery/GetQueryResults/StopQuery for CloudWatch Logs so
clients using Logs Insights (e.g. boto3 start_query + get_query_results)
work against Floci instead of receiving UnsupportedOperation.

LogsInsightsQuery is a minimal engine covering the common subset: fields,
filter (= / !=), sort, dedup, limit; it resolves @timestamp/@message and
dotted JSON paths (e.g. params.job_id, level). StartQuery times are epoch
seconds while event timestamps are millis, scaled accordingly.

Queries follow a time-driven lifecycle: results are computed eagerly, but
a query reports Running until a configurable completion delay elapses
(FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS, default 0 =
instant for local dev), then Complete; StopQuery cancels a running query
and otherwise returns AWS-faithful errors (InvalidParameterException when
already ended, ResourceNotFoundException for an unknown id). Status is
computed on read from an injectable clock, with no background threads.
GetQueryResults returns ResourceNotFoundException for unknown ids,
reports recordsMatched independent of the Running/Cancelled row masking,
hands out a defensive copy of result rows, and drops rows once cancelled.
Results are cached by queryId with LRU eviction.

Covered by unit tests and an AWS SDK v2 compatibility test exercising the
full StartQuery/GetQueryResults/StopQuery lifecycle (stable against both
instant and delayed completion).

* test(cloudwatch): cover Logs Insights search across multiple log groups

Verify a single StartQuery spanning several log groups finds the same
params.id wherever it was logged (results merged and globally sorted by
@timestamp), and that a matching event in an un-queried group is excluded.

* test(cloudwatch): cover Logs Insights query-language edge cases

Add unit tests for limit (applied after sort), ascending sort on a nested
JSON field, the default @timestamp/@message projection, missing-field
handling (empty projection plus null-safe inequality filtering), graceful
ignoring of unsupported commands (parse/stats), and the recordsScanned vs
recordsMatched statistics.

* fix(cloudwatch): deterministic Logs Insights ordering for same-ms events and dedup

Tie-break the @timestamp/@ingestionTime sort comparators by ingestion sequence
then eventId (matching the event store's EVENT_ORDER), and apply the AWS-documented
default @timestamp desc sort when a dedup stage has no preceding sort — so the
surviving duplicate is the newest, deterministically, rather than depending on
storage-scan order.

* fix(cloudwatch): validate log groups and harden Logs Insights query parsing

StartQuery now de-duplicates the requested log groups (the same group can
arrive via multiple selectors) so it is scanned and counted once, and it
returns ResourceNotFoundException for a log group that does not exist
instead of a successful empty query — matching real AWS. The stage parser
splits on pipes only outside quotes, so a filter value containing '|'
(e.g. filter x = 'a|b') is no longer broken into fragments.

StartQuery still accepts multiple selectors and de-duplicates group names
service-side; strict AWS mutual-exclusivity rejection (InvalidParameterException
for more than one of logGroupName/logGroupNames/logGroupIdentifiers) is deferred
to a handler-side follow-up, since the handler collapses all three selectors
into one service argument.

* fix(cloudwatch): reject empty StartQuery selectors and parse quoted filter operators

StartQuery now rejects a request with no usable log-group selector
(InvalidParameterException) instead of returning a successful empty query.
parseFilter finds the equality/inequality operator outside quoted values,
so a value that itself contains '=' / '==' / '!=' (e.g. filter x = 'a==b')
is no longer misparsed.

* fix(cloudwatch): reject StartQuery requests with more than one log-group selector

AWS requires exactly one of logGroupName, logGroupNames, or logGroupIdentifiers.
The handler now rejects a request that provides more than one selector type with
InvalidParameterException, instead of silently querying the union. The
zero-selector case is already rejected by the service.

* fix(cloudwatch): count serialized StartQuery selector fields, not just non-empty ones

The mutual-exclusivity guard counted a selector only when its value was non-blank,
but the merge path added any present field — so a blank logGroupName alongside a
real logGroupNames slipped past the guard. Count serialized fields uniformly (has),
so a blank or empty selector field can't bypass the check; a lone empty selector
still yields no groups and is rejected by the service.

---------

Co-authored-by: Beytullah Gunduz <beytullah-gunduz@users.noreply.github.com>
This commit is contained in:
Beytullah GunduzandBeytullah Gunduz authored and GitHub committed 2026-07-05 08:48:43 -05:00
1 parent f490bbefad
commit 89fadbad81
7 files changed
+1493 -1

No files matched your search

@@ -0,0 +1,186 @@
package com.floci.test;
import org.junit.jupiter.api.*;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.*;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
/**
* CloudWatch Logs Insights compatibility: StartQuery / GetQueryResults / StopQuery.
*
* <p>Seeds a log group with structured JSON events and exercises the same query shape real
* clients send — filter on a nested JSON field ({@code params.job_id}), drop a log level,
* sort by {@code @timestamp}, and dedup. StartQuery times are epoch <em>seconds</em> while
* event timestamps are millis.
*/
@DisplayName("CloudWatch Logs Insights")
class CloudWatchLogsInsightsTest {
private static CloudWatchLogsClient logs;
private static final String GROUP = "/test/" + TestFixtures.uniqueName("insights");
private static final String STREAM = "stream-01";
private static String jobId;
private static long baseMs;
@BeforeAll
static void setUp() {
logs = TestFixtures.cloudWatchLogsClient();
logs.createLogGroup(b -> b.logGroupName(GROUP));
logs.createLogStream(b -> b.logGroupName(GROUP).logStreamName(STREAM));
baseMs = System.currentTimeMillis();
jobId = TestFixtures.uniqueName("job");
logs.putLogEvents(b -> b
.logGroupName(GROUP)
.logStreamName(STREAM)
.logEvents(
InputLogEvent.builder().timestamp(baseMs - 3000).message(json("INFO", "job started", jobId)).build(),
InputLogEvent.builder().timestamp(baseMs - 2000).message(json("TRACE", "verbose noise", jobId)).build(),
InputLogEvent.builder().timestamp(baseMs - 1000).message(json("INFO", "unrelated", "other-job")).build(),
InputLogEvent.builder().timestamp(baseMs).message(json("ERROR", "job boom", jobId)).build()
));
}
@AfterAll
static void tearDown() {
if (logs != null) {
try {
logs.deleteLogGroup(b -> b.logGroupName(GROUP));
} catch (RuntimeException ignored) {
// best-effort cleanup
}
logs.close();
}
}
@Test
@DisplayName("StartQuery returns a queryId")
void startQueryReturnsQueryId() {
StartQueryResponse start = startTestQuery();
assertThat(start.queryId()).isNotBlank();
}
@Test
@DisplayName("GetQueryResults filters by JSON field, drops TRACE, sorts desc and dedups")
void getQueryResultsFiltersSortsDedups() {
// On real AWS, events are not queryable for several seconds after ingestion; retry the
// full start+poll cycle until rows appear or the ~60s deadline elapses.
GetQueryResultsResponse res = pollUntilComplete(startTestQuery().queryId());
long deadline = System.currentTimeMillis() + 60_000;
while (res.results().isEmpty() && System.currentTimeMillis() < deadline) {
res = pollUntilComplete(startTestQuery().queryId());
}
assertThat(res.status()).isEqualTo(QueryStatus.COMPLETE);
// job_id filter keeps 3 events; level != TRACE drops 1 -> 2 rows.
assertThat(res.results()).hasSize(2);
// Every row projects @timestamp and @message.
assertThat(res.results()).allSatisfy(row -> {
assertThat(row).anySatisfy(f -> assertThat(f.field()).isEqualTo("@timestamp"));
assertThat(row).anySatisfy(f -> assertThat(f.field()).isEqualTo("@message"));
});
// sort @timestamp desc -> newest (ERROR "job boom") first, then INFO "job started".
assertThat(messageOf(res.results().get(0))).contains("job boom");
assertThat(messageOf(res.results().get(1))).contains("job started");
// The TRACE line and the unrelated job must be excluded.
List<String> messages = res.results().stream()
.map(CloudWatchLogsInsightsTest::messageOf)
.toList();
assertThat(messages).noneMatch(m -> m.contains("verbose noise") || m.contains("unrelated"));
}
@Test
@DisplayName("StopQuery on a finished query fails with InvalidParameterException")
void stopFinishedQueryFailsNotRunning() {
StartQueryResponse start = startTestQuery();
pollUntilComplete(start.queryId()); // ensure the query has ended
// AWS: stopping a query that is not running returns an error ("...is not running").
assertThatThrownBy(() -> logs.stopQuery(b -> b.queryId(start.queryId())))
.isInstanceOfSatisfying(CloudWatchLogsException.class,
e -> assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterException"));
}
@Test
@DisplayName("StopQuery on a running query returns success")
void stopRunningQuerySucceeds() {
StartQueryResponse start = startTestQuery();
// Only meaningful where the server models an async Running window: real AWS, or Floci with a
// non-zero query-completion-delay (FLOCI_SERVICES_CLOUDWATCHLOGS_QUERY_COMPLETION_DELAY_MS=2000).
// With Floci's default (instant completion) there is no Running phase, so this case is skipped
// rather than asserted.
String status = logs.getQueryResults(b -> b.queryId(start.queryId())).statusAsString();
Assumptions.assumeTrue("Running".equals(status) || "Scheduled".equals(status),
"no Running window (instant completion) — nothing to stop");
// On real AWS the query can complete in the gap between the status check and the stop call;
// treat InvalidParameterException from stopQuery as a valid outcome rather than a failure.
try {
StopQueryResponse stop = logs.stopQuery(b -> b.queryId(start.queryId()));
assertThat(stop.success()).isTrue();
} catch (CloudWatchLogsException e) {
if ("InvalidParameterException".equals(e.awsErrorDetails().errorCode())) {
Assumptions.abort("query completed before stop");
}
throw e;
}
}
// ──────────────────────────── helpers ────────────────────────────
private static StartQueryResponse startTestQuery() {
long nowSec = baseMs / 1000;
return logs.startQuery(b -> b
.logGroupNames(GROUP)
.startTime(nowSec - 300)
.endTime(nowSec + 300)
.queryString(query()));
}
private static String query() {
return "fields @timestamp, @message"
+ " | filter params.job_id = '" + jobId + "'"
+ " | filter level != 'TRACE'"
+ " | sort @timestamp desc"
+ " | dedup @timestamp, @message";
}
private static GetQueryResultsResponse pollUntilComplete(String queryId) {
GetQueryResultsResponse res = null;
for (int i = 0; i < 75; i++) { // ~15s budget; real AWS Insights queries run asynchronously
res = logs.getQueryResults(b -> b.queryId(queryId));
QueryStatus status = res.status();
if (status == QueryStatus.COMPLETE || status == QueryStatus.FAILED || status == QueryStatus.CANCELLED) {
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
return res;
}
private static String messageOf(List<ResultField> row) {
return row.stream()
.filter(f -> "@message".equals(f.field()))
.map(ResultField::value)
.findFirst()
.orElse("");
}
private static String json(String level, String message, String job) {
return "{\"level\":\"" + level + "\",\"message\":\"" + message + "\",\"params\":{\"job_id\":\"" + job + "\"}}";
}
}