Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 44 additions & 7 deletions lambda/log-analyzer/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -744,22 +744,30 @@ def list_recent_findings(team_id, account_id, now=None):

def resolve_stale_recommendations(team_id, existing, seen_ids, now=None):
"""Mark open findings resolved when this complete run didn't see them and
no matching line came for lifecycle.QUIET_DAYS. One missed run never
resolves a finding: the next sighting would have to make a new one."""
they have been quiet for their quiet period (lifecycle.quiet_days_for).
One missed run never resolves a finding. Open findings also carry their
quiet period (`quiet_days`) so the page can say when one resolves."""
now_dt = now or datetime.now(timezone.utc)
now_iso = now_dt.isoformat()
resolved_count = 0
for item in lifecycle.stale(existing, seen_ids, now_dt):
stale = lifecycle.stale(existing, seen_ids, now_dt)
stale_ids = {i.get("rec_id") for i in stale}
for item in stale:
days = lifecycle.quiet_days_for(item)
reason = f"Resolved: no new lines for {days} day{'s' if days != 1 else ''}"
try:
aws_insights_table.update_item(
Key={"pk": team_id, "sk": item["sk"]},
UpdateExpression="SET #s = :s, resolved_at = :t, updated_at = :t",
UpdateExpression="SET #s = :s, resolved_at = :t, updated_at = :t, resolved_reason = :r, quiet_days = :q",
ConditionExpression="#s = :pending",
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={":s": "resolved", ":t": now_iso, ":pending": "pending"},
ExpressionAttributeValues={
":s": "resolved", ":t": now_iso, ":pending": "pending", ":r": reason, ":q": days,
},
)
resolved_count += 1
item["status"], item["resolved_at"] = "resolved", now_iso
item["resolved_reason"], item["quiet_days"] = reason, days
emit_event(
team_id,
"log_finding.resolved",
Expand All @@ -773,6 +781,27 @@ def resolve_stale_recommendations(team_id, existing, seen_ids, now=None):
except ClientError as e:
if e.response.get("Error", {}).get("Code") != "ConditionalCheckFailedException":
logger.warning(f"Failed to resolve {item['sk']}: {e}")
for item in existing:
# Seen this run: the sighting already wrote its quiet period.
if item.get("rec_id") in stale_ids or item.get("rec_id") in seen_ids:
continue
if item.get("status", "pending") != "pending" or item.get("merged_into"):
continue
days = lifecycle.quiet_days_for(item)
if attribution.as_int(item.get("quiet_days")) == days:
continue
try:
aws_insights_table.update_item(
Key={"pk": team_id, "sk": item["sk"]},
UpdateExpression="SET quiet_days = :q",
ConditionExpression="#s = :pending",
ExpressionAttributeNames={"#s": "status"},
ExpressionAttributeValues={":q": days, ":pending": "pending"},
)
item["quiet_days"] = days
except ClientError as e:
if e.response.get("Error", {}).get("Code") != "ConditionalCheckFailedException":
logger.warning(f"Failed to set quiet days on {item['sk']}: {e}")
if resolved_count:
logger.info(f"{team_id}: {resolved_count} recommendations resolved")

Expand Down Expand Up @@ -928,6 +957,12 @@ def store_finding(team_id, account_id, cand, existing, cw_logs=None, window=None
sighting["signature_hashes"],
)
history = lifecycle.add_history(match.get("daily_lines"), today, added)
reopening = match.get("status") == "resolved"
quiet = lifecycle.quiet_days_for({
"daily_lines": history,
"last_resolved_at": (match.get("resolved_at") or now) if reopening else match.get("last_resolved_at"),
"reopened_at": now if reopening else match.get("reopened_at"),
})
values = {
":t": now,
":ttl": ttl_epoch,
Expand All @@ -944,12 +979,13 @@ def store_finding(team_id, account_id, cand, existing, cw_logs=None, window=None
":hist": history,
":fp": sighting["fingerprint"],
":sig": sighting["signature"][:300],
":quiet": quiet,
}
sets = (
"last_seen_at = :l, first_seen_at = :f, updated_at = :t, error_count = :c, "
"seen_count = :seen, count_basis = :basis, samples = :samples, log_account_id = :acct, "
"signature_hashes = :sigs, log_streams = :streams, also_in = :others, daily_lines = :hist, "
"fingerprint = if_not_exists(fingerprint, :fp), #sig = if_not_exists(#sig, :sig)"
"fingerprint = if_not_exists(fingerprint, :fp), #sig = if_not_exists(#sig, :sig), quiet_days = :quiet"
)
names = {"#sig": "signature"}
reopened = match.get("status") == "resolved"
Expand Down Expand Up @@ -992,7 +1028,7 @@ def store_finding(team_id, account_id, cand, existing, cw_logs=None, window=None
match.update({
"last_seen_at": values[":l"], "first_seen_at": values[":f"],
"seen_count": seen, "count_basis": "events", "signature_hashes": hashes,
"daily_lines": history,
"daily_lines": history, "quiet_days": quiet,
})
if reopened:
match.update({"status": "pending", "reopened_at": now})
Expand Down Expand Up @@ -1024,6 +1060,7 @@ def store_finding(team_id, account_id, cand, existing, cw_logs=None, window=None
"log_streams": streams,
"also_in": others,
"daily_lines": lifecycle.add_history([], today, stats["count"]),
"quiet_days": lifecycle.DEFAULT_QUIET_DAYS,
"created_at": now,
"updated_at": now,
"first_seen_at": attribution.iso(first) or now,
Expand Down
52 changes: 44 additions & 8 deletions lambda/log-analyzer/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,17 @@
- A resolved finding seen again is reopened (status back to pending,
`reopened_at`, `reopen_count`, `last_resolved_at`), never duplicated.
- An ignored finding stays ignored; its counts and history still grow.
- An open finding is resolved only after QUIET_DAYS without a matching line,
never because one run missed it.
- An open finding (New, Acknowledged or being fixed) is resolved once it has
been quiet for its quiet period, never because one run missed it.
Acknowledging never holds a finding open.

The quiet period (quiet_days_for):
- A burst that stopped (lines on one run of consecutive days, or no daily
history): DEFAULT_QUIET_DAYS.
- An error that keeps coming back: twice the longest silence it has come back
from, counting gaps between days with lines and the time from a resolve to
the reopen, so it isn't resolved while it is likely to return.
- Never less than MIN_QUIET_DAYS (24 hours), never more than MAX_QUIET_DAYS.

Pure functions only; the handler does the reads and writes.
"""
Expand All @@ -26,8 +35,10 @@
import attribution
import fingerprint

# A finding is resolved after this long without a matching line.
QUIET_DAYS = 7
# A burst that stopped is resolved after this long without a matching line.
DEFAULT_QUIET_DAYS = 3
MIN_QUIET_DAYS = 1
MAX_QUIET_DAYS = 14
# A resolved finding seen again within this long is reopened.
REOPEN_DAYS = 30
# Stored findings expire this long after their last sighting (DynamoDB TTL),
Expand Down Expand Up @@ -137,9 +148,33 @@ def literal_in_lines(e):
return None


def stale(existing, seen_ids, now=None, quiet_days=QUIET_DAYS):
"""Open findings to resolve: pending, not seen this run, and no matching
line for `quiet_days`. A finding with no time at all is left open."""
def quiet_days_for(item):
"""How long `item` must go without a matching line before it is
resolved (see the module notes)."""
days = sorted(
str(h["day"])
for h in item.get("daily_lines") or []
if isinstance(h, dict) and h.get("day") and attribution.as_int(h.get("lines")) > 0
)
gaps = []
for a, b in zip(days, days[1:]):
try:
gap = (datetime.fromisoformat(b) - datetime.fromisoformat(a)).days
except ValueError:
continue
if gap > 1:
gaps.append(gap)
resolved, back = _ts(item.get("last_resolved_at")), _ts(item.get("reopened_at"))
if resolved and back and back > resolved:
gaps.append(max(1, round((back - resolved).total_seconds() / 86400)))
quiet = 2 * max(gaps) if gaps else DEFAULT_QUIET_DAYS
return max(MIN_QUIET_DAYS, min(MAX_QUIET_DAYS, quiet))


def stale(existing, seen_ids, now=None, quiet_days=None):
"""Open findings to resolve: pending (New, Acknowledged or being fixed),
not seen this run, and quiet for their quiet period (`quiet_days` when
given). A finding with no time at all is left open."""
now = now or datetime.now(timezone.utc)
out = []
for item in existing:
Expand All @@ -148,7 +183,8 @@ def stale(existing, seen_ids, now=None, quiet_days=QUIET_DAYS):
if item.get("merged_into"):
continue
last = last_sighting(item)
if last is not None and now - last >= timedelta(days=quiet_days):
days = quiet_days if quiet_days is not None else quiet_days_for(item)
if last is not None and now - last >= timedelta(days=days):
out.append(item)
return out

Expand Down
47 changes: 46 additions & 1 deletion lambda/tests/test_log_dedup.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,52 @@ def test_one_missed_run_never_resolves(self):
t = Table()
with Patch(aws_insights_table=t, emit_event=lambda *_a, **_k: None):
h.resolve_stale_recommendations("TEAM#t", [seen_yesterday, quiet, ignored], set())
self.assertEqual([u["Key"]["sk"] for u in t.updates], ["REC#r2"])
resolves = [u for u in t.updates if ":s" in u["ExpressionAttributeValues"]]
self.assertEqual([u["Key"]["sk"] for u in resolves], ["REC#r2"])

def test_an_acknowledged_finding_resolves_once_quiet(self):
# Acknowledged is still pending: it never holds a finding open.
ack = {"rec_id": "a1", "sk": "REC#a1", "status": "pending", "acknowledged_at": iso_ago(days=1),
"last_seen_at": iso_ago(days=L.DEFAULT_QUIET_DAYS, hours=1),
"daily_lines": [{"day": "2026-10-26", "lines": 900}]}
fresh = dict(ack, rec_id="a2", sk="REC#a2", last_seen_at=iso_ago(days=L.DEFAULT_QUIET_DAYS - 1))
self.assertEqual([i["rec_id"] for i in L.stale([ack, fresh], set())], ["a1"])
t = Table()
with Patch(aws_insights_table=t, emit_event=lambda *_a, **_k: None):
h.resolve_stale_recommendations("TEAM#t", [ack, fresh], set())
resolved = [u for u in t.updates if u["Key"]["sk"] == "REC#a1"][0]
vals = resolved["ExpressionAttributeValues"]
self.assertEqual(vals[":s"], "resolved")
self.assertEqual(vals[":r"], f"Resolved: no new lines for {L.DEFAULT_QUIET_DAYS} days")
# The open one carries its quiet period, so the page can say when.
stamped = [u for u in t.updates if u["Key"]["sk"] == "REC#a2"][0]
self.assertEqual(stamped["ExpressionAttributeValues"][":q"], L.DEFAULT_QUIET_DAYS)

def test_a_burst_that_stopped_waits_the_default_quiet_period(self):
burst = {"daily_lines": [{"day": "2026-10-25", "lines": 40}, {"day": "2026-10-26", "lines": 6000},
{"day": "2026-10-27", "lines": 0}]}
self.assertEqual(L.quiet_days_for(burst), L.DEFAULT_QUIET_DAYS)
self.assertEqual(L.quiet_days_for({}), L.DEFAULT_QUIET_DAYS)

def test_an_error_that_keeps_coming_back_needs_a_longer_quiet_period(self):
every_4_days = {"daily_lines": [{"day": d, "lines": 5} for d in ("2026-10-01", "2026-10-05", "2026-10-09")]}
self.assertEqual(L.quiet_days_for(every_4_days), 8)
returned = {"last_resolved_at": iso_ago(days=9), "reopened_at": iso_ago(days=5)}
self.assertEqual(L.quiet_days_for(returned), 8)
rare = {"daily_lines": [{"day": "2026-09-01", "lines": 1}, {"day": "2026-09-29", "lines": 1}]}
self.assertEqual(L.quiet_days_for(rare), L.MAX_QUIET_DAYS)
# Quiet for 5 days is not enough for the every-4-days error.
item = dict(every_4_days, rec_id="r", sk="REC#r", status="pending", last_seen_at=iso_ago(days=5))
self.assertEqual(L.stale([item], set()), [])
self.assertGreaterEqual(L.MIN_QUIET_DAYS, 1)

def test_seen_again_after_an_auto_resolve_reopens(self):
# Covered for the write by the reopen tests; here the quiet period
# grows with the silence it came back from.
item = {"rec_id": "x", "status": "pending", "last_resolved_at": iso_ago(days=6),
"reopened_at": iso_ago(days=3), "last_seen_at": iso_ago(days=3)}
self.assertEqual(L.quiet_days_for(item), 6)
self.assertEqual(L.stale([item], set()), [])

def test_history_adds_new_lines_per_day(self):
hist = L.add_history([], "2026-10-25", 5)
Expand Down
58 changes: 56 additions & 2 deletions services/common/src/log_findings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,17 @@ impl Severity {

// ─── Findings ───────────────────────────────────────────────────────────────

/// The analyzer's quiet period for a burst that stopped
/// (lambda/log-analyzer/lifecycle.py DEFAULT_QUIET_DAYS).
pub const DEFAULT_QUIET_DAYS: u64 = 3;

/// One finding as stored.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Finding {
pub rec_id: String,
/// `pending`, `approved` (a plan was made), `dismissed` or `resolved`
/// (the analyzer saw no matching line for a week; seen again, it is
/// reopened as `pending` with `reopened_at`).
/// (the analyzer saw no matching line for its quiet period; seen again,
/// it is reopened as `pending` with `reopened_at`).
pub status: String,
pub severity: Severity,
pub title: String,
Expand Down Expand Up @@ -184,6 +188,13 @@ pub struct Finding {
/// The finding this duplicate was folded into (merge_duplicates.py);
/// a merged finding is not listed.
pub merged_into: String,
/// When the analyzer resolved it, and why ("Resolved: no new lines for
/// N days"); empty while open.
pub resolved_at: String,
pub resolved_reason: String,
/// Days without a matching line before the analyzer resolves it
/// (lifecycle.quiet_days_for); missing on older items.
pub quiet_days: Option<u64>,
}

impl Finding {
Expand Down Expand Up @@ -240,6 +251,9 @@ impl Finding {
reopened_at: s(item, "reopened_at"),
reopen_count: n(item, "reopen_count").unwrap_or(0),
merged_into: s(item, "merged_into"),
resolved_at: s(item, "resolved_at"),
resolved_reason: s(item, "resolved_reason"),
quiet_days: n(item, "quiet_days"),
})
}

Expand All @@ -259,6 +273,27 @@ impl Finding {
.to_string()
}

/// The quiet period this finding resolves after: its own, or the
/// analyzer's default for a burst that stopped.
pub fn quiet_days(&self) -> u64 {
self.quiet_days
.filter(|d| *d > 0)
.unwrap_or(DEFAULT_QUIET_DAYS)
}

/// When an open finding resolves on its own if no new line comes
/// (its last line plus its quiet period); None once it isn't open or
/// has no last time.
pub fn resolves_at(&self) -> Option<String> {
if self.status != "pending" || !self.merged_into.is_empty() {
return None;
}
let last = chrono::DateTime::parse_from_rfc3339(&self.last_seen_at).ok()?;
let at =
last.with_timezone(&chrono::Utc) + chrono::Duration::days(self.quiet_days() as i64);
Some(at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
}

/// The ticket every fix run for this finding's error shares.
pub fn ticket_id(&self) -> String {
ticket_id(&self.fingerprint())
Expand Down Expand Up @@ -1627,6 +1662,25 @@ pub fn console_url(region: &str, log_group: &str) -> Option<String> {

#[cfg(test)]
mod tests {

#[test]
fn an_open_finding_says_when_it_resolves_on_its_own() {
let mut f = Finding {
status: "pending".into(),
last_seen_at: "2026-10-31T03:38:10Z".into(),
..Default::default()
};
// An older item without a quiet period gets the analyzer's default.
assert_eq!(f.quiet_days(), DEFAULT_QUIET_DAYS);
assert_eq!(f.resolves_at().as_deref(), Some("2026-11-03T03:38:10Z"));
f.quiet_days = Some(8);
assert_eq!(f.resolves_at().as_deref(), Some("2026-11-08T03:38:10Z"));
f.status = "resolved".into();
assert_eq!(f.resolves_at(), None);
f.status = "dismissed".into();
assert_eq!(f.resolves_at(), None);
}

use super::*;
use std::sync::Mutex;

Expand Down
6 changes: 6 additions & 0 deletions services/gateway/src/routes/log_findings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,12 @@ pub fn finding_json(
"also_in": f.also_in.iter().map(|c| json!({ "log_group": c.name, "lines": c.lines })).collect::<Vec<_>>(),
"reopened_at": (!f.reopened_at.is_empty()).then_some(&f.reopened_at),
"reopen_count": f.reopen_count,
// Open: when it resolves on its own unless seen again. Resolved: when
// and why the analyzer resolved it.
"quiet_days": f.quiet_days(),
"resolves_at": f.resolves_at(),
"resolved_at": (!f.resolved_at.is_empty()).then_some(&f.resolved_at),
"resolved_reason": (!f.resolved_reason.is_empty()).then_some(&f.resolved_reason),
})
}

Expand Down
Loading