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
25 changes: 23 additions & 2 deletions aw_transform/classify.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
from typing import Pattern, List, Iterable, Tuple, Dict, Optional, Any
from functools import reduce
import re
Expand Down Expand Up @@ -43,7 +44,18 @@ def match(self, e: Event) -> bool:
def categorize(
events: List[Event], classes: List[Tuple[Category, Rule]]
) -> List[Event]:
return [_categorize_one(e, classes) for e in events]
cache: Dict[str, Category] = {}
for e in events:
try:
key = json.dumps(e.data, sort_keys=True)
except TypeError:
key = str(id(e.data))
if key not in cache:
cache[key] = _pick_category(
[_cls for _cls, rule in classes if rule.match(e)]
)
e.data["$category"] = list(cache[key])
Comment on lines +47 to +57

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Optimization lacks profiling measurements

These caches implement a performance optimization without profiling or benchmark measurements, so reviewers cannot validate the claimed bottleneck, representative improvement, or the cost of serializing every event payload.

Rule Used: Before implementing performance optimizations, mea... (source)

Learned From
gptme/gptme#707

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

return events


def _categorize_one(e: Event, classes: List[Tuple[Category, Rule]]) -> Event:
Expand All @@ -54,7 +66,16 @@ def _categorize_one(e: Event, classes: List[Tuple[Category, Rule]]) -> Event:


def tag(events: List[Event], classes: List[Tuple[Tag, Rule]]) -> List[Event]:
return [_tag_one(e, classes) for e in events]
cache: Dict[str, List[Tag]] = {}
for e in events:
try:
key = json.dumps(e.data, sort_keys=True)
except TypeError:
key = str(id(e.data))
if key not in cache:
cache[key] = [_cls for _cls, rule in classes if rule.match(e)]
e.data["$tags"] = list(cache[key])
return events


def _tag_one(e: Event, classes: List[Tuple[Tag, Rule]]) -> Event:
Expand Down
30 changes: 30 additions & 0 deletions tests/test_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,36 @@ def test_categorize():
assert events[3].data["$category"] == ["Uncategorized"]


def test_categorize_cache_correctness():
"""Cache reuses category for identical data; distinct data gets its own category."""
now = datetime.now(timezone.utc)

classes = [
(["Browser"], Rule({"regex": "Firefox"})),
(["Editor"], Rule({"regex": "vim"})),
]
firefox_data = {"app": "Firefox", "title": "Home"}
vim_data = {"app": "vim", "title": "classify.py"}

# 50 Firefox events, 1 vim event, 50 more Firefox events
events = (
[Event(timestamp=now, duration=0, data=dict(firefox_data)) for _ in range(50)]
+ [Event(timestamp=now, duration=0, data=dict(vim_data))]
+ [Event(timestamp=now, duration=0, data=dict(firefox_data)) for _ in range(50)]
)
result = categorize(events, classes)

for e in result[:50]:
assert e.data["$category"] == ["Browser"]
assert result[50].data["$category"] == ["Editor"]
for e in result[51:]:
assert e.data["$category"] == ["Browser"]

# Mutating one event's category must not affect others sharing the same data fingerprint
result[0].data["$category"].append("MUTATED")
assert result[1].data["$category"] == ["Browser"]


def test_tags():
now = datetime.now(timezone.utc)

Expand Down
Loading