mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudwatch): fail Logs Insights queries with unsupported syntax instead of silently dropping it (#3139)
An unsupported filter, command, or invalid argument to a recognized command (e.g. limit abc, a bare sort/dedup) was ignored with only a server log warning, so the query came back Complete with a result set that did not reflect what was asked. It now reports GetQueryResults status Failed instead. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
653c1397a2
commit
121a9292b7
3 files changed
+161
-32
No files matched your search
+55
-17
@@ -731,15 +731,21 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
// ──────────────────────────── Logs Insights Queries ────────────────────────────
|
||||
|
||||
/** A query's status and (once Complete) its projected rows — the AWS GetQueryResults shape. */
|
||||
/**
|
||||
* A query's status and (once Complete) its projected rows: the AWS GetQueryResults shape.
|
||||
* {@code failureReason} is {@code null} unless {@code status} is {@code Failed}; it is not
|
||||
* part of the AWS wire response (GetQueryResults carries no such field) but is exposed here
|
||||
* for callers and tests that want to know why an unsupported query failed.
|
||||
*/
|
||||
public record QueryState(String status, List<LinkedHashMap<String, String>> rows,
|
||||
long recordsScanned, long recordsMatched) {}
|
||||
long recordsScanned, long recordsMatched, String failureReason) {}
|
||||
|
||||
/** Lifecycle state of a stored Insights query; {@link #label()} is the AWS wire form. */
|
||||
private enum InsightsQueryStatus {
|
||||
RUNNING("Running"),
|
||||
COMPLETE("Complete"),
|
||||
CANCELLED("Cancelled");
|
||||
CANCELLED("Cancelled"),
|
||||
FAILED("Failed");
|
||||
|
||||
private final String label;
|
||||
|
||||
@@ -755,42 +761,61 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
/**
|
||||
* A stored Insights query. Results are computed eagerly at StartQuery, but the query reports
|
||||
* {@code Running} until {@code completeAtMs} (an artificial delay emulating AWS's asynchronous
|
||||
* execution), then {@code Complete} — unless cancelled by StopQuery, after which it is
|
||||
* {@code Cancelled}. State transitions are time-driven and computed on read. {@code recordsMatched}
|
||||
* is captured at construction so it survives the Running/Cancelled row masking and the row-drop on cancel.
|
||||
* execution), then either {@code Complete} or, if the query string contained syntax this engine
|
||||
* cannot evaluate, {@code Failed}, unless cancelled by StopQuery first, after which it is
|
||||
* {@code Cancelled}. State transitions are time-driven and computed on read. For a Complete or
|
||||
* Cancelled query, {@code recordsMatched} is captured at construction so it survives the
|
||||
* Running/Cancelled row masking and the row-drop on cancel; a Failed query never evaluated any
|
||||
* matches, so its {@code recordsMatched} is always zero.
|
||||
*/
|
||||
private static final class QueryRecord {
|
||||
private List<LinkedHashMap<String, String>> rows;
|
||||
private final long recordsScanned;
|
||||
private final long recordsMatched;
|
||||
private final long completeAtMs;
|
||||
private final String failureReason;
|
||||
private boolean cancelled;
|
||||
|
||||
QueryRecord(List<LinkedHashMap<String, String>> rows, long recordsScanned, long completeAtMs) {
|
||||
this(rows, recordsScanned, completeAtMs, null);
|
||||
}
|
||||
|
||||
private QueryRecord(List<LinkedHashMap<String, String>> rows, long recordsScanned, long completeAtMs,
|
||||
String failureReason) {
|
||||
this.rows = rows;
|
||||
this.recordsScanned = recordsScanned;
|
||||
this.recordsMatched = rows.size();
|
||||
this.completeAtMs = completeAtMs;
|
||||
this.failureReason = failureReason;
|
||||
}
|
||||
|
||||
/** A query whose string could not be fully evaluated: it never produces rows and ends up {@code Failed}. */
|
||||
static QueryRecord failed(long recordsScanned, long completeAtMs, String failureReason) {
|
||||
return new QueryRecord(List.of(), recordsScanned, completeAtMs, failureReason);
|
||||
}
|
||||
|
||||
private InsightsQueryStatus status(long nowMs) {
|
||||
if (cancelled) {
|
||||
return InsightsQueryStatus.CANCELLED;
|
||||
}
|
||||
return nowMs >= completeAtMs ? InsightsQueryStatus.COMPLETE : InsightsQueryStatus.RUNNING;
|
||||
if (nowMs < completeAtMs) {
|
||||
return InsightsQueryStatus.RUNNING;
|
||||
}
|
||||
return failureReason != null ? InsightsQueryStatus.FAILED : InsightsQueryStatus.COMPLETE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Snapshot this query in the AWS GetQueryResults shape. Rows are exposed only once
|
||||
* {@code Complete}, and always as a defensive copy (the cached list is never handed out); while
|
||||
* Running or Cancelled the rows are masked empty, but {@code recordsMatched} still reports the
|
||||
* full match count.
|
||||
* full match count. A Failed query exposes neither: it has no rows and no matches to report,
|
||||
* so both fields are empty and zero respectively.
|
||||
*/
|
||||
synchronized QueryState snapshot(long nowMs) {
|
||||
InsightsQueryStatus status = status(nowMs);
|
||||
List<LinkedHashMap<String, String>> visible =
|
||||
status == InsightsQueryStatus.COMPLETE ? List.copyOf(rows) : List.of();
|
||||
return new QueryState(status.label(), visible, recordsScanned, recordsMatched);
|
||||
return new QueryState(status.label(), visible, recordsScanned, recordsMatched, failureReason);
|
||||
}
|
||||
|
||||
/** Cancels the query iff still running, dropping its now-unreachable rows. Returns true if this call stopped it. */
|
||||
@@ -807,7 +832,8 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
/**
|
||||
* Start a CloudWatch Logs Insights query and cache it under a new queryId. Results are computed
|
||||
* eagerly (the scan is in-memory); the query then reports {@code Running} until the configured
|
||||
* completion delay elapses (default 0 = immediate), emulating AWS's async execution.
|
||||
* completion delay elapses (default 0 = immediate), emulating AWS's async execution, then either
|
||||
* {@code Complete} or, if the query string could not be fully evaluated, {@code Failed}.
|
||||
* {@code startTimeSeconds}/{@code endTimeSeconds} are epoch <em>seconds</em> (the StartQuery
|
||||
* contract); {@link LogEvent} timestamps are epoch millis, so they are scaled for comparison.
|
||||
*/
|
||||
@@ -844,12 +870,22 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
int effectiveLimit = (limit != null && limit > 0) ? Math.min(limit, maxEventsPerQuery) : maxEventsPerQuery;
|
||||
List<LinkedHashMap<String, String>> rows =
|
||||
LogsInsightsQuery.parse(queryString).evaluate(gathered, effectiveLimit);
|
||||
|
||||
LogsInsightsQuery parsedQuery = LogsInsightsQuery.parse(queryString);
|
||||
String queryId = UUID.randomUUID().toString();
|
||||
long completeAtMs = clock.getAsLong() + queryCompletionDelayMs;
|
||||
|
||||
if (parsedQuery.isUnsupported()) {
|
||||
// A query containing syntax this engine cannot evaluate must not come back as a
|
||||
// "successful" empty or partial result set: fail it, so the caller can tell the
|
||||
// difference between "the filter matched nothing" and "the filter was never applied".
|
||||
insightsQueries.put(queryId, QueryRecord.failed(gathered.size(), completeAtMs, parsedQuery.getUnsupportedReason()));
|
||||
LOG.warnv("Logs Insights query {0} will fail: {1}", queryId, parsedQuery.getUnsupportedReason());
|
||||
return queryId;
|
||||
}
|
||||
|
||||
int effectiveLimit = (limit != null && limit > 0) ? Math.min(limit, maxEventsPerQuery) : maxEventsPerQuery;
|
||||
List<LinkedHashMap<String, String>> rows = parsedQuery.evaluate(gathered, effectiveLimit);
|
||||
|
||||
insightsQueries.put(queryId, new QueryRecord(rows, gathered.size(), completeAtMs));
|
||||
LOG.infov("Logs Insights query {0}: scanned {1} event(s) across {2} group(s) -> {3} row(s)",
|
||||
queryId, gathered.size(), distinctGroups.size(), rows.size());
|
||||
@@ -858,9 +894,11 @@ public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
/**
|
||||
* Return a query's status and, once {@code Complete}, its rows. Mirrors AWS: while {@code Running}
|
||||
* or after a StopQuery ({@code Cancelled}) the result set is empty (though {@code recordsMatched}
|
||||
* still reports the full match count); only a Complete query exposes rows. An unknown queryId is an
|
||||
* error on real AWS — and a query that has fallen out of the bounded LRU cache 404s the same way.
|
||||
* or after a StopQuery ({@code Cancelled}) the result set is empty, though {@code recordsMatched}
|
||||
* still reports the full match count; once the query string is found to contain unsupported syntax
|
||||
* ({@code Failed}) both the rows and {@code recordsMatched} are empty, since such a query is never
|
||||
* evaluated. Only a Complete query exposes rows. An unknown queryId is an error on real AWS, and a
|
||||
* query that has fallen out of the bounded LRU cache 404s the same way.
|
||||
*/
|
||||
public QueryState getQueryResults(String queryId) {
|
||||
QueryRecord rec = insightsQueries.get(queryId);
|
||||
|
||||
+41
-5
@@ -31,8 +31,10 @@ import java.util.Set;
|
||||
*
|
||||
* <p>This is intentionally <em>not</em> a full Insights implementation: unsupported commands
|
||||
* (e.g. {@code stats}, {@code parse}) and unsupported filter operators (e.g. {@code >=},
|
||||
* {@code like}) are ignored with a warning. Pipes ({@code |}) inside quoted filter values are
|
||||
* respected and do not split the query into stages.
|
||||
* {@code like}) mark the query as unsupported (see {@link #isUnsupported()}) rather than being
|
||||
* silently dropped, so the caller can fail the query instead of returning a result set that does
|
||||
* not correspond to what was asked. Pipes ({@code |}) inside quoted filter values are respected
|
||||
* and do not split the query into stages.
|
||||
*/
|
||||
final class LogsInsightsQuery {
|
||||
|
||||
@@ -47,6 +49,7 @@ final class LogsInsightsQuery {
|
||||
private boolean sortDesc;
|
||||
private List<String> dedupFields;
|
||||
private Integer limit;
|
||||
private String unsupportedReason;
|
||||
|
||||
private record Filter(String field, boolean negate, String value) {}
|
||||
|
||||
@@ -73,6 +76,21 @@ final class LogsInsightsQuery {
|
||||
return q;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the query contains a command or filter expression this engine cannot evaluate.
|
||||
* Such a query must not be executed as if the unsupported stage were absent: the caller
|
||||
* (see {@link #getUnsupportedReason()}) should fail the query rather than return a result
|
||||
* set that silently omits it.
|
||||
*/
|
||||
boolean isUnsupported() {
|
||||
return unsupportedReason != null;
|
||||
}
|
||||
|
||||
/** The first unsupported command or filter expression encountered, or {@code null} if none. */
|
||||
String getUnsupportedReason() {
|
||||
return unsupportedReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -109,6 +127,8 @@ final class LogsInsightsQuery {
|
||||
Filter f = parseFilter(args);
|
||||
if (f != null) {
|
||||
filters.add(f);
|
||||
} else {
|
||||
noteUnsupported("Unsupported filter expression: " + args);
|
||||
}
|
||||
}
|
||||
case "sort", "order" -> {
|
||||
@@ -116,20 +136,37 @@ final class LogsInsightsQuery {
|
||||
if (s.length > 0 && !s[0].isEmpty()) {
|
||||
sortField = s[0].trim();
|
||||
sortDesc = s.length > 1 && s[1].trim().equalsIgnoreCase("desc");
|
||||
} else {
|
||||
noteUnsupported("Sort command is missing its field");
|
||||
}
|
||||
}
|
||||
case "dedup" -> {
|
||||
dedupFields = new ArrayList<>();
|
||||
splitCsv(args, dedupFields);
|
||||
if (dedupFields.isEmpty()) {
|
||||
noteUnsupported("Dedup command is missing its field(s): " + args);
|
||||
}
|
||||
}
|
||||
case "limit" -> {
|
||||
try {
|
||||
limit = Integer.parseInt(args.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.warnv("Ignoring invalid Logs Insights limit: {0}", args);
|
||||
noteUnsupported("Invalid limit argument: " + args);
|
||||
}
|
||||
}
|
||||
default -> LOG.warnv("Ignoring unsupported Logs Insights command: {0}", cmd);
|
||||
default -> noteUnsupported("Unsupported command: " + cmd);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the first unsupported command or filter expression the query contains. Only the
|
||||
* first is kept: it is enough to fail the whole query, and later stages may reference fields
|
||||
* or state the earlier failure never let this engine establish.
|
||||
*/
|
||||
private void noteUnsupported(String reason) {
|
||||
LOG.warnv("Logs Insights query contains unsupported syntax, failing the query: {0}", reason);
|
||||
if (unsupportedReason == null) {
|
||||
unsupportedReason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +208,6 @@ final class LogsInsightsQuery {
|
||||
}
|
||||
}
|
||||
}
|
||||
LOG.warnv("Ignoring unsupported Logs Insights filter: {0}", expr);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+65
-10
@@ -459,14 +459,15 @@ class CloudWatchLogsInsightsQueryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedCommandsAreIgnored() {
|
||||
void unsupportedCommandsFailTheQueryInsteadOfBeingIgnored() {
|
||||
String group = "data-sources/connectors";
|
||||
String stream = "s-1";
|
||||
createGroupStream(service, group, stream);
|
||||
put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "kept");
|
||||
put(group, stream, BASE_MS + 2000, "TRACE", "JOB-1", "dropped");
|
||||
|
||||
// 'parse' / 'stats' are unsupported: ignored with a warning, while the supported stages still run.
|
||||
// 'parse' / 'stats' are unsupported: the query must fail rather than silently apply only the
|
||||
// stages it understands and return a result set that does not correspond to the query asked.
|
||||
String query = """
|
||||
fields @message
|
||||
| filter level != 'TRACE'
|
||||
@@ -477,13 +478,15 @@ class CloudWatchLogsInsightsQueryTest {
|
||||
String queryId = service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION);
|
||||
|
||||
CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
|
||||
assertEquals("Complete", state.status());
|
||||
assertEquals(1, state.rows().size(), "TRACE dropped by filter; parse/stats ignored, not applied");
|
||||
assertTrue(state.rows().get(0).get("@message").contains("kept"));
|
||||
assertEquals("Failed", state.status());
|
||||
assertTrue(state.rows().isEmpty(), "a failed query exposes no rows");
|
||||
assertNotNull(state.failureReason());
|
||||
assertTrue(state.failureReason().contains("parse"), "failure reason names the unsupported command: "
|
||||
+ state.failureReason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedFilterOperatorsDropTheStageInsteadOfMisparsing() {
|
||||
void unsupportedFilterOperatorsFailTheQueryInsteadOfMisparsingOrDropping() {
|
||||
String group = "search/query-operators";
|
||||
String stream = "s-1";
|
||||
createGroupStream(service, group, stream);
|
||||
@@ -491,13 +494,58 @@ class CloudWatchLogsInsightsQueryTest {
|
||||
put(group, stream, BASE_MS + 2000, "ERROR", "JOB-1", "error-line");
|
||||
|
||||
// '>=', '<=' 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, so each one
|
||||
// drops the whole stage with a warning and every row comes back.
|
||||
// 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.
|
||||
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']")) {
|
||||
assertEquals(2, rowsFor(group, "fields @message | filter " + expr).size(),
|
||||
"unsupported operator must drop the whole filter stage: " + expr);
|
||||
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);
|
||||
assertNotNull(state.failureReason(), "failure reason must be set: " + expr);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void startQuerySucceedsAndReportsFailureOnlyViaGetQueryResults() {
|
||||
// A query the engine cannot evaluate must still be accepted by StartQuery (it is a valid
|
||||
// request shape, just unsupported syntax); the failure surfaces asynchronously through
|
||||
// GetQueryResults, exactly like a real Insights query failing partway through execution.
|
||||
String group = "search/unsupported-syntax";
|
||||
String stream = "s-1";
|
||||
createGroupStream(service, group, stream);
|
||||
put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "hello");
|
||||
|
||||
long startSec = BASE_MS / 1000 - 10;
|
||||
String queryId = service.startQuery(
|
||||
List.of(group), startSec, startSec + 86400, "filter @message like /ERROR/", null, REGION);
|
||||
assertNotNull(queryId);
|
||||
|
||||
CloudWatchLogsService.QueryState state = service.getQueryResults(queryId);
|
||||
assertEquals("Failed", state.status());
|
||||
assertTrue(state.rows().isEmpty());
|
||||
assertNotNull(state.failureReason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidArgumentsToRecognizedCommandsFailTheQuery() {
|
||||
// A recognized command with an argument it cannot parse must fail the query too, not just an
|
||||
// unrecognized command or a fully-unsupported filter operator: silently keeping the default
|
||||
// limit, or silently running with no sort/dedup, would be just as misleading to the caller.
|
||||
String group = "search/invalid-command-arguments";
|
||||
String stream = "s-1";
|
||||
createGroupStream(service, group, stream);
|
||||
put(group, stream, BASE_MS + 1000, "INFO", "JOB-1", "one");
|
||||
put(group, stream, BASE_MS + 2000, "INFO", "JOB-1", "two");
|
||||
|
||||
for (String query : List.of(
|
||||
"fields @message | limit abc",
|
||||
"fields @message | sort",
|
||||
"fields @message | dedup")) {
|
||||
CloudWatchLogsService.QueryState state = startQueryFor(group, query);
|
||||
assertEquals("Failed", state.status(), "invalid command argument must fail the query: " + query);
|
||||
assertTrue(state.rows().isEmpty(), "a failed query exposes no rows: " + query);
|
||||
assertNotNull(state.failureReason(), "failure reason must be set: " + query);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -641,6 +689,13 @@ class CloudWatchLogsInsightsQueryTest {
|
||||
return state.rows();
|
||||
}
|
||||
|
||||
/** 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;
|
||||
return service.getQueryResults(
|
||||
service.startQuery(List.of(group), startSec, startSec + 86400, query, null, REGION));
|
||||
}
|
||||
|
||||
private void createGroupStream(CloudWatchLogsService svc, String group, String stream) {
|
||||
svc.createLogGroup(group, null, null, REGION);
|
||||
svc.createLogStream(group, stream, REGION);
|
||||
|
||||
Reference in new issue
Block a user