diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsInsightsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsInsightsTest.java index e11081552e..46c509bbe4 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsInsightsTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudWatchLogsInsightsTest.java @@ -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() { diff --git a/docs/services/cloudwatch.md b/docs/services/cloudwatch.md index 8795e928bf..7085948afb 100644 --- a/docs/services/cloudwatch.md +++ b/docs/services/cloudwatch.md @@ -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 = 'v'` | Equality. `!=` and `==` are also accepted; `where` is an alias | +| `filter = '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 [asc\|desc]` | `order` is an alias | | `dedup ` | 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 : scanned ... -> 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. diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java index e4e9f7f04a..4d25dcc5c0 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsService.java @@ -1151,6 +1151,11 @@ public class CloudWatchLogsService implements ResourceProvider, Resettable { */ public String startQuery(List 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; diff --git a/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java b/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java index f3b1d9edff..d9fdb16d2d 100644 --- a/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java +++ b/src/main/java/io/floci/aws/services/cloudwatch/logs/LogsInsightsQuery.java @@ -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; *
    *
  • {@code fields a, b, ...} — projection (defaults to {@code @timestamp, @message})
  • *
  • {@code filter = 'v'} / {@code filter != 'v'} — equality / inequality
  • + *
  • {@code filter a = 'x' or b = 'y'}: any comparison matches; {@code or} in any case, with parentheses
  • *
  • {@code sort [asc|desc]}
  • *
  • {@code dedup } — keep the first row per unique tuple (applied after sort)
  • *
  • {@code limit N}
  • @@ -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 fields = new ArrayList<>(); - private final List filters = new ArrayList<>(); + private final List> filters = new ArrayList<>(); private String sortField; private boolean sortDesc; private List 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 splitStages(String query) { List 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 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 parseDisjunction(String expr) { + String body = stripGroup(expr.trim()); + List terms = splitOr(body); + if (terms.size() == 1) { + Filter f = parseFilter(body); + return f != null ? List.of(f) : null; + } + List anyOf = new ArrayList<>(); + for (String term : terms) { + List 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 splitOr(String s) { + List 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 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 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 comparatorFor(String field) { if ("@timestamp".equals(field)) { return Comparator.comparingLong(r -> r.event.getTimestamp()) diff --git a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java index 4b38bafd33..e1aa9bb1ba 100644 --- a/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java +++ b/src/test/java/io/floci/aws/services/cloudwatch/logs/CloudWatchLogsInsightsQueryTest.java @@ -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 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 } returns, sorted. */ + private List 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;