fix(logs): support or in Logs Insights filters (#7924)

* fix(logs): support or in Logs Insights filters

A filter or where stage now keeps rows matching any or-joined comparison, case-insensitive, with parenthesized and nested groups. Syntax the engine does not model (and, not, ||, escapes, backtick fields, expressions in place of a field, empty stages) fails the query instead of returning a silently wrong result set.

Closes #7907

* fix(logs): limit Insights bare filter values to numbers and enforce the queryString length

An unquoted filter value is now a number compared by value, as on AWS (n = 2 matches 2 and 2.0).
Other unquoted values, such as a word or 1+1, fail the query instead of being read as text.
StartQuery rejects a queryString over 10,000 characters with InvalidParameterException, which
also bounds the nesting the or parser walks.

* fix(logs): keep Insights field parsing stack-safe and count queryString in code points

A long dotted field such as a.a.a... overflowed the stack in the field regex, which repeated a
group recursively; the repetition is now possessive and runs in a loop. The queryString limit
uses the shared Smithy length check, which counts code points as AWS does, so a query of
emoji under 10,000 code points is no longer rejected.

* refactor(logs): share one quote-skipping scanner across the Insights parser
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-11-10 16:18:56 -04:00
1 parent 0e244e5724
commit f37afdad81
5 files changed
+324 -71

No files matched your search

@@ -67,13 +67,7 @@ class CloudWatchLogsInsightsTest {
@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());
}
GetQueryResultsResponse res = resultsOf(query());
assertThat(res.status()).isEqualTo(QueryStatus.COMPLETE);
@@ -97,6 +91,19 @@ class CloudWatchLogsInsightsTest {
assertThat(messages).noneMatch(m -> m.contains("verbose noise") || m.contains("unrelated"));
}
@Test
@DisplayName("GetQueryResults keeps rows matching either side of an or filter")
void getQueryResultsOrFilter() {
GetQueryResultsResponse res = resultsOf("fields @timestamp, @message"
+ " | filter params.job_id = 'other-job' or level = 'ERROR'"
+ " | sort @timestamp desc");
assertThat(res.status()).isEqualTo(QueryStatus.COMPLETE);
assertThat(res.results()).hasSize(2);
assertThat(messageOf(res.results().get(0))).contains("job boom");
assertThat(messageOf(res.results().get(1))).contains("unrelated");
}
@Test
@DisplayName("StopQuery on a finished query fails with InvalidParameterException")
void stopFinishedQueryFailsNotRunning() {
@@ -138,12 +145,27 @@ class CloudWatchLogsInsightsTest {
// ──────────────────────────── helpers ────────────────────────────
private static StartQueryResponse startTestQuery() {
return startTestQuery(query());
}
private static StartQueryResponse startTestQuery(String queryString) {
long nowSec = baseMs / 1000;
return logs.startQuery(b -> b
.logGroupNames(GROUP)
.startTime(nowSec - 300)
.endTime(nowSec + 300)
.queryString(query()));
.queryString(queryString));
}
private static GetQueryResultsResponse resultsOf(String queryString) {
// 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(queryString).queryId());
long deadline = System.currentTimeMillis() + 60_000;
while (res.results().isEmpty() && System.currentTimeMillis() < deadline) {
res = pollUntilComplete(startTestQuery(queryString).queryId());
}
return res;
}
private static String query() {
+7 -8
View File
@@ -273,12 +273,13 @@ The bare-colon spelling is a client-compatibility tolerance: the
documents the canonical ARN, not that spelling. This tolerance does not change other APIs' ARN handling.
`StartQuery` / `GetQueryResults` / `StopQuery` run a **subset** of the Logs Insights
query language. Supported commands:
query language. As on AWS, `StartQuery` rejects a `queryString` longer than 10,000 characters
with `InvalidParameterException`. Supported commands:
| Command | Notes |
|---|---|
| `fields a, b, ...` | Projection. Defaults to `@timestamp, @message`. `display` is an alias |
| `filter <field> = 'v'` | Equality. `!=` and `==` are also accepted; `where` is an alias |
| `filter <field> = 'v'` | Equality. `!=` and `==` are also accepted; `where` is an alias. An unquoted value must be a number and compares by value, so `n = 2` matches `2` and `2.0`. Comparisons can be joined with `or` (any case) and grouped with parentheses, for example `filter (type = 'A' or type = 'B')` |
| `sort <field> [asc\|desc]` | `order` is an alias |
| `dedup <field, ...>` | Keeps the first row per unique tuple, applied after sorting |
| `limit N` | The effective cap is the smallest of this value, the `StartQuery` `limit` parameter, and `FLOCI_SERVICES_CLOUDWATCHLOGS_MAX_EVENTS_PER_QUERY` |
@@ -296,15 +297,13 @@ degrade silently, so it is worth knowing how each case behaves:
| Input | Result |
|---|---|
| An unsupported command (`stats`, `parse`, ...) | The query fails. Logged as `Unsupported command: stats` |
| A `filter` whose operator is not `=`, `!=` or `==` — for example `<`, `<=`, `>`, `>=`, `like /ERROR/` or `=~ /ERROR/` | The query fails. Logged as `Unsupported filter expression: ...`. Exception: an unquoted `=` anywhere in the expression, as in `like /a=b/`, is taken as the equality operator, so that query completes with **no** rows and no warning |
| A `filter` combining conditions with `and` / `or` — for example `filter level = 'ERROR' and status = 200` | Only the leftmost operator is parsed; the rest of the line becomes the compared value. With `=` nothing matches and you get **no** rows; with `!=` everything matches and you get **every** row (up to the limit). `status` is `Complete` and no warning is logged |
| A `filter` whose operator is not `=`, `!=` or `==`, for example `<`, `<=`, `>`, `>=`, `like /ERROR/` or `=~ /ERROR/` | The query fails. Logged as `Unsupported filter expression: ...` |
| A `filter` using `and`, `not` or `\|\|`, or with text after the value, as in `filter level = 'ERROR' x` | The query fails. AWS evaluates `and` and `not`, ignores the trailing text, and rejects an unparenthesized `\|\|` at `StartQuery` with `MalformedQueryException` (use `or`) |
| A blank query, or an empty stage as in a trailing `\|` | The query fails. AWS rejects it at `StartQuery` |
| A `filter` with a backslash escape, a backtick-quoted field name, an expression such as `1+1` in place of the field, or an unquoted value that is not a number, such as `level = ERROR` or `n = 1+1` | The query fails. AWS interprets them |
| A projected field that does not exist | Rendered as an empty string. No warning |
| A `sort` direction other than `asc` / `desc` | Treated as ascending. No warning |
When a `Complete` result set looks narrower or wider than intended, check the query for a
compound `filter` or a stray `=` first: those cases produce neither a failure nor a warning. The
only log line is the usual INFO summary, `Logs Insights query <id>: scanned ... -> <n> row(s)`.
For matching events by a pattern, `FilterLogEvents` is the more predictable option today: it
applies the filter pattern syntax (`?ERROR ?WARN`, `{ $.level = "ERROR" }`, and so on) as AWS does.
@@ -1151,6 +1151,11 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable {
*/
public String startQuery(List<String> logGroupNames, long startTimeSeconds, long endTimeSeconds,
String queryString, Integer limit, String region) {
String tooLong = SmithyValidationErrors.Violations.WITHOUT_VALUES.lengthOutOfRange(
"queryString", queryString, 0, 10_000);
if (tooLong != null) {
throw SmithyValidationErrors.exception("InvalidParameterException", tooLong);
}
long startMs = startTimeSeconds * 1000L;
long endMs = endTimeSeconds * 1000L;
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.cloudwatch.logs.model.LogEvent;
import org.jboss.logging.Logger;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -14,6 +15,7 @@ import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Minimal CloudWatch Logs Insights query engine.
@@ -22,6 +24,7 @@ import java.util.Set;
* <ul>
* <li>{@code fields a, b, ...} — projection (defaults to {@code @timestamp, @message})</li>
* <li>{@code filter <field> = 'v'} / {@code filter <field> != 'v'} — equality / inequality</li>
* <li>{@code filter a = 'x' or b = 'y'}: any comparison matches; {@code or} in any case, with parentheses</li>
* <li>{@code sort <field> [asc|desc]}</li>
* <li>{@code dedup <field, ...>} — keep the first row per unique tuple (applied after sort)</li>
* <li>{@code limit N}</li>
@@ -42,25 +45,29 @@ final class LogsInsightsQuery {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final DateTimeFormatter TS_FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneOffset.UTC);
private static final Pattern NUMBER = Pattern.compile("-?\\d+(\\.\\d+)?");
// Possessive, so a long dotted path is matched in a loop rather than one stack frame per segment.
private static final Pattern FIELD = Pattern.compile("[@A-Za-z_]\\w*(?:\\.\\w+)*+");
private final List<String> fields = new ArrayList<>();
private final List<Filter> filters = new ArrayList<>();
private final List<List<Filter>> filters = new ArrayList<>();
private String sortField;
private boolean sortDesc;
private List<String> dedupFields;
private Integer limit;
private String unsupportedReason;
private record Filter(String field, boolean negate, String value) {}
private record Filter(String field, boolean negate, String value, boolean numeric) {}
private LogsInsightsQuery() {}
static LogsInsightsQuery parse(String queryString) {
LogsInsightsQuery q = new LogsInsightsQuery();
if (queryString != null && !queryString.isBlank()) {
if (queryString != null) {
for (String rawStage : splitStages(queryString)) {
String stage = rawStage.trim();
if (stage.isEmpty()) {
q.noteUnsupported("Empty query stage");
continue;
}
String[] parts = stage.split("\\s+", 2);
@@ -92,41 +99,43 @@ final class LogsInsightsQuery {
}
/**
* Split a query into pipeline stages on {@code |}, ignoring pipes inside single- or double-quoted
* values (so {@code filter x = 'a|b'} stays one stage). Escaped quotes are not interpreted.
* Split a query into pipeline stages on {@code |} outside quoted text (so {@code filter x = 'a|b'}
* stays one stage).
*/
private static List<String> splitStages(String query) {
List<String> stages = new ArrayList<>();
StringBuilder current = new StringBuilder();
char quote = 0;
for (int i = 0; i < query.length(); i++) {
char c = query.charAt(i);
if (quote != 0) {
if (c == quote) {
quote = 0;
}
current.append(c);
} else if (c == '\'' || c == '"') {
quote = c;
current.append(c);
} else if (c == '|') {
stages.add(current.toString());
current.setLength(0);
} else {
current.append(c);
int start = 0;
for (int i = unquoted(query, 0); i < query.length(); i = unquoted(query, i + 1)) {
if (query.charAt(i) == '|') {
stages.add(query.substring(start, i));
start = i + 1;
}
}
stages.add(current.toString());
stages.add(query.substring(start));
return stages;
}
/**
* The first index at or after {@code from} (itself outside quoted text) that is outside single- or
* double-quoted text and is not a quote itself, or {@code s.length()}. Escaped quotes are not
* interpreted; an unclosed quote runs to the end.
*/
private static int unquoted(String s, int from) {
int i = from;
while (i < s.length() && (s.charAt(i) == '\'' || s.charAt(i) == '"')) {
int close = s.indexOf(s.charAt(i), i + 1);
i = close < 0 ? s.length() : close + 1;
}
return i;
}
private void applyStage(String cmd, String args) {
switch (cmd) {
case "fields", "display" -> splitCsv(args, fields);
case "filter", "where" -> {
Filter f = parseFilter(args);
if (f != null) {
filters.add(f);
List<Filter> anyOf = args.indexOf('\\') < 0 ? parseDisjunction(args) : null;
if (anyOf != null) {
filters.add(anyOf);
} else {
noteUnsupported("Unsupported filter expression: " + args);
}
@@ -179,20 +188,83 @@ final class LogsInsightsQuery {
}
}
/**
* Parse comparisons joined with {@code or} (any case), optionally grouped in parentheses.
* Returns {@code null} when any term is not a single supported comparison.
*/
private static List<Filter> parseDisjunction(String expr) {
String body = stripGroup(expr.trim());
List<String> terms = splitOr(body);
if (terms.size() == 1) {
Filter f = parseFilter(body);
return f != null ? List.of(f) : null;
}
List<Filter> anyOf = new ArrayList<>();
for (String term : terms) {
List<Filter> part = parseDisjunction(term);
if (part == null) {
return null;
}
anyOf.addAll(part);
}
return anyOf;
}
/** Remove parentheses that enclose the whole expression. */
private static String stripGroup(String expr) {
String s = expr;
while (s.startsWith("(") && closingParen(s) == s.length() - 1) {
s = s.substring(1, s.length() - 1).trim();
}
return s;
}
/** Index of the parenthesis closing the one at index 0, ignoring quoted text, or -1. */
private static int closingParen(String s) {
int depth = 0;
for (int i = unquoted(s, 0); i < s.length(); i = unquoted(s, i + 1)) {
char c = s.charAt(i);
if (c == '(') {
depth++;
} else if (c == ')' && --depth == 0) {
return i;
}
}
return -1;
}
/** Split on the word {@code or} (any case) outside quotes and parentheses. */
private static List<String> splitOr(String s) {
List<String> terms = new ArrayList<>();
int depth = 0;
int start = 0;
for (int i = unquoted(s, 0); i < s.length(); i = unquoted(s, i + 1)) {
char c = s.charAt(i);
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
} else if (depth == 0 && s.regionMatches(true, i, "or", 0, 2)
&& (i == 0 || isDelimiter(s.charAt(i - 1)))
&& (i + 2 == s.length() || isDelimiter(s.charAt(i + 2)))) {
terms.add(s.substring(start, i));
start = i + 2;
}
}
terms.add(s.substring(start));
return terms;
}
private static boolean isDelimiter(char c) {
return Character.isWhitespace(c) || c == '\'' || c == '"' || c == '(' || c == ')';
}
private static Filter parseFilter(String expr) {
// Scan for the operator OUTSIDE any quoted value, taking the leftmost one and checking
// '!=' / '==' before '='. This avoids mistaking an operator inside a quoted literal
// (e.g. filter x = 'a==b') for the real one.
char quote = 0;
for (int i = 0; i < expr.length(); i++) {
// Take the leftmost operator outside quoted text, checking '!=' / '==' before '=', so an
// operator inside a quoted literal (e.g. filter x = 'a==b') is not mistaken for the real one.
for (int i = unquoted(expr, 0); i < expr.length(); i = unquoted(expr, i + 1)) {
char c = expr.charAt(i);
if (quote != 0) {
if (c == quote) {
quote = 0;
}
} else if (c == '\'' || c == '"') {
quote = c;
} else if (expr.startsWith(">=", i) || expr.startsWith("<=", i) || expr.startsWith("=~", i)) {
if (expr.startsWith(">=", i) || expr.startsWith("<=", i) || expr.startsWith("=~", i)) {
// The '=' in >=, <= and =~ would be read as equality below, mangling the field
// (>=, <=) or the value (=~) into a dead match; stop so they warn instead.
break;
@@ -203,23 +275,28 @@ final class LogsInsightsQuery {
: null;
if (op != null) {
String field = expr.substring(0, i).trim();
String value = unquote(expr.substring(i + op.length()).trim());
return new Filter(field, op.equals("!="), value);
String raw = expr.substring(i + op.length()).trim();
String value = literal(raw);
if (value == null || !FIELD.matcher(field).matches()) {
return null;
}
return new Filter(field, op.equals("!="), value, NUMBER.matcher(raw).matches());
}
}
}
return null;
}
private static String unquote(String s) {
if (s.length() >= 2) {
char first = s.charAt(0);
char last = s.charAt(s.length() - 1);
if ((first == '\'' && last == '\'') || (first == '"' && last == '"')) {
return s.substring(1, s.length() - 1);
}
/**
* The text of a quoted literal, or a bare number; {@code null} for anything else. AWS evaluates
* other unquoted values (a word, {@code 1+1}) as expressions, which this engine does not support.
*/
private static String literal(String s) {
if (!s.isEmpty() && (s.charAt(0) == '\'' || s.charAt(0) == '"')) {
int close = s.indexOf(s.charAt(0), 1);
return close == s.length() - 1 ? s.substring(1, close) : null;
}
return s;
return NUMBER.matcher(s).matches() ? s : null;
}
/**
@@ -234,7 +311,7 @@ final class LogsInsightsQuery {
rows.add(new Row(e, tryParse(e.getMessage())));
}
// filter (logical AND across all filter stages)
// filter (logical AND across filter stages, OR within one)
List<Row> matched = new ArrayList<>();
for (Row row : rows) {
if (passesFilters(row)) {
@@ -291,17 +368,30 @@ final class LogsInsightsQuery {
}
private boolean passesFilters(Row row) {
for (Filter f : filters) {
String actual = resolve(row, f.field());
boolean equals = actual != null && actual.equals(f.value());
boolean fails = f.negate() ? equals : !equals;
if (fails) {
for (List<Filter> anyOf : filters) {
if (anyOf.stream().noneMatch(f -> matches(row, f))) {
return false;
}
}
return true;
}
private boolean matches(Row row, Filter f) {
String actual = resolve(row, f.field());
boolean equal = actual != null && (f.numeric() ? sameNumber(actual, f.value()) : actual.equals(f.value()));
return f.negate() != equal;
}
/** A bare number compares by value on AWS, so {@code n = 2} matches 2, 2.0 and 02. */
private static boolean sameNumber(String actual, String expected) {
try {
return new BigDecimal(actual).compareTo(new BigDecimal(expected)) == 0;
} catch (NumberFormatException ignored) {
// A non-numeric field value is simply not equal to a number.
return false;
}
}
private Comparator<Row> comparatorFor(String field) {
if ("@timestamp".equals(field)) {
return Comparator.<Row>comparingLong(r -> r.event.getTimestamp())
@@ -207,6 +207,30 @@ class CloudWatchLogsInsightsQueryTest {
assertEquals("InvalidParameterException", blank.getErrorCode());
}
@Test
void queryStringLongerThanTheAwsLimitIsRejected() {
String group = "search/query-length";
String stream = "s-1";
createGroupStream(service, group, stream);
putRaw(service, group, stream, BASE_MS + 1000, "{\"type\":\"B\",\"id\":\"b1\"}");
putRaw(service, group, stream, BASE_MS + 2000, "{\"type\":\"C\",\"id\":\"c1\"}");
// The deepest nesting and the longest dotted field that fit in AWS's 10000-character limit still parse.
String nested = "fields id | filter " + "a=1 or (".repeat(1100) + "type = 'B'" + ")".repeat(1100);
assertEquals(List.of("b1"), rowsFor(group, nested).stream().map(row -> row.get("id")).toList());
assertEquals(List.of(), idsFor(group, "a" + ".a".repeat(4900) + " = 1"));
// AWS counts code points: 4990 emoji are 9980 UTF-16 units but leave the query under the limit.
assertEquals(List.of(), idsFor(group, "id = '" + "\uD83D\uDE00".repeat(4990) + "'"));
long startSec = BASE_MS / 1000 - 10;
String tooLong = "fields id" + " ".repeat(10_000 - 8);
AwsException ex = assertThrows(AwsException.class, () ->
service.startQuery(List.of(group), startSec, startSec + 86400, tooLong, null, REGION));
assertEquals("InvalidParameterException", ex.getErrorCode());
assertEquals("1 validation error detected: Value at 'queryString' failed to satisfy constraint: "
+ "Member must have length less than or equal to 10000", ex.getMessage());
}
@Test
void filterValueContainingEqualsIsNotMisparsed() {
String group = "connectors/equals";
@@ -497,9 +521,34 @@ class CloudWatchLogsInsightsQueryTest {
// '>=', '<=' and '=~' used to lose their comparison character to the equality scan, leaving a
// dead field ("level >") that silently matched nothing. None of these is supported: each one
// must now fail the whole query rather than silently drop the filter and return every row.
// The same holds for '||', 'and', 'not' and leftover text after a value: each fails rather
// than degrading silently into a different comparison.
for (String expr : List.of("level >= 'INFO'", "level <= 'INFO'", "level =~ /INFO/", ">= 'INFO'",
"level > 'INFO'", "level < 'INFO'", "level like /INFO/", "level not like /INFO/",
"level in ['INFO']")) {
"level in ['INFO']",
"level = 'INFO' || level = 'ERROR'",
"level = 'INFO' || level = 'ERROR' | sort @timestamp desc",
"(level = 'INFO' || level = 'ERROR')",
"level = 'INFO' or level = 'ERROR' ||",
"level = 'INFO' || sort @timestamp desc",
"level = 'INFO' or",
"level = 'INFO' and level = 'ERROR'",
"not level = 'INFO'",
"level = 'INFO' or level like /E/",
"level like /a=b/",
"level != INFO=oops",
"level = INFO=oops",
"level = 'INFO\\' or level = 'ERROR'",
"`level` = 'INFO'",
"1+1 = 2 or level = 'ERROR'",
"level. = 'INFO'",
"level = 'INFO' x",
"(level = 'INFO'",
"level = 'INFO",
"level = INFO",
"level = web-db",
"level = 1+1",
"level != 1+1 or level = 'ERROR'")) {
CloudWatchLogsService.QueryState state = startQueryFor(group, "fields @message | filter " + expr);
assertEquals("Failed", state.status(), "unsupported operator must fail the query: " + expr);
assertTrue(state.rows().isEmpty(), "a failed query exposes no rows: " + expr);
@@ -550,6 +599,20 @@ class CloudWatchLogsInsightsQueryTest {
}
}
@Test
void emptyStageFailsTheQuery() {
String group = "search/empty-stage";
String stream = "s-1";
createGroupStream(service, group, stream);
put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "one");
for (String query : List.of("", " ", "fields @message |", "fields @message | | sort @timestamp desc")) {
CloudWatchLogsService.QueryState state = startQueryFor(group, query);
assertEquals("Failed", state.status(), "an empty stage must fail the query: '" + query + "'");
assertTrue(state.rows().isEmpty(), "a failed query exposes no rows: '" + query + "'");
}
}
@Test
void supportedFilterOperatorsStillParse() {
String group = "search/query-equality";
@@ -568,6 +631,75 @@ class CloudWatchLogsInsightsQueryTest {
rowsFor(group, "fields params.id | filter params.id = 'REQ>=42'").get(0).get("params.id"));
}
@Test
void bareNumberComparesAsANumber() {
String group = "search/query-number";
String stream = "s-1";
createGroupStream(service, group, stream);
// These events and the expected ids below were observed on AWS with the same queries.
putRaw(service, group, stream, BASE_MS + 1000, "{\"n\":2,\"id\":\"a1\"}");
putRaw(service, group, stream, BASE_MS + 2000, "{\"n\":3,\"id\":\"b1\"}");
putRaw(service, group, stream, BASE_MS + 3000, "{\"n\":2.0,\"id\":\"d1\"}");
for (String filter : List.of("n = 2", "n = 2.0", "n = 02", "n == 2")) {
assertEquals(List.of("a1", "d1"), idsFor(group, filter), filter);
}
assertEquals(List.of(), idsFor(group, "n = -2"), "n = -2");
assertEquals(List.of("b1"), idsFor(group, "n != 2"), "n != 2");
}
@Test
void orFilterKeepsRowsMatchingEitherComparison() {
String group = "search/query-or";
String stream = "s-1";
createGroupStream(service, group, stream);
// These events and the expected ids below were observed on AWS with the same queries.
putRaw(service, group, stream, BASE_MS + 1000, "{\"type\":\"A\",\"level\":\"INFO\",\"id\":\"a1\"}");
putRaw(service, group, stream, BASE_MS + 2000, "{\"type\":\"B\",\"level\":\"INFO\",\"id\":\"b1\"}");
putRaw(service, group, stream, BASE_MS + 3000, "{\"type\":\"C\",\"level\":\"INFO\",\"id\":\"c1\"}");
putRaw(service, group, stream, BASE_MS + 4000, "{\"type\":\"A|B\",\"level\":\"INFO\",\"id\":\"p1\"}");
putRaw(service, group, stream, BASE_MS + 5000, "{\"type\":\"A\",\"level\":\"WARN\",\"id\":\"a2\"}");
putRaw(service, group, stream, BASE_MS + 6000,
"{\"type\":\"A or B\",\"color\":\"red\",\"order\":\"first\",\"id\":\"o1\"}");
assertEquals(List.of("a1", "a2"), idsFor(group, "type = 'A'"), "type = 'A'");
assertEquals(List.of("b1"), idsFor(group, "type = 'B'"), "type = 'B'");
assertEquals(List.of("p1"), idsFor(group, "type = 'A|B'"), "type = 'A|B'");
assertEquals(List.of("o1"), idsFor(group, "type = 'A or B'"), "type = 'A or B'");
assertEquals(List.of("c1", "o1"), idsFor(group, "color = 'red' or type = 'C'"),
"color = 'red' or type = 'C'");
assertEquals(List.of("c1", "o1"), idsFor(group, "order = 'first' or type = 'C'"),
"order = 'first' or type = 'C'");
for (String filter : List.of(
"type = 'A' or type = 'B'",
"type = 'A' OR type = 'B'",
"type = 'A' Or type = 'B'",
"type='A'or type='B'",
"type = \"A\" or type = \"B\"",
"type == 'A' or type == 'B'",
"(type = 'A' or type = 'B')",
"(type = 'A') or (type = 'B')",
"((type = 'A') or type = 'B')",
"(type='A')or(type='B')")) {
assertEquals(List.of("a1", "a2", "b1"), idsFor(group, filter), filter);
}
assertEquals(List.of("a1", "a2", "b1", "c1"), idsFor(group, "type = 'A' or type = 'B' or type = 'C'"),
"type = 'A' or type = 'B' or type = 'C'");
assertEquals(List.of("a1", "a2", "b1", "c1"), idsFor(group, "type = 'A' or (type = 'B' or type = 'C')"),
"type = 'A' or (type = 'B' or type = 'C')");
assertEquals(List.of("a2", "b1", "c1", "o1", "p1"), idsFor(group, "type != 'A' or level = 'WARN'"),
"type != 'A' or level = 'WARN'");
assertEquals(List.of("b1"), idsFor(group, "(type = 'A)' or type = 'B')"), "(type = 'A)' or type = 'B')");
List<String> sortedDesc = rowsFor(group, "fields id | filter type = 'A' or type = 'B' | sort @timestamp desc")
.stream().map(row -> row.get("id")).toList();
assertEquals(List.of("a2", "b1", "a1"), sortedDesc, "type = 'A' or type = 'B' | sort @timestamp desc");
assertEquals(List.of("a1", "b1"), idsFor(group, "type = 'A' or type = 'B' | filter level = 'INFO'"),
"type = 'A' or type = 'B' | filter level = 'INFO'");
}
@Test
void statisticsReportScannedAndMatched() {
String group = "data-studio/insights";
@@ -690,6 +822,11 @@ class CloudWatchLogsInsightsQueryTest {
return state.rows();
}
/** The {@code id} of each row {@code fields id | filter <filter>} returns, sorted. */
private List<String> idsFor(String group, String filter) {
return rowsFor(group, "fields id | filter " + filter).stream().map(row -> row.get("id")).sorted().toList();
}
/** Run {@code query} over the full window on the default service and return its final state. */
private CloudWatchLogsService.QueryState startQueryFor(String group, String query) {
long startSec = BASE_MS / 1000 - 10;