Skip to content

⚡️ Speed up method JfrProfile._parse_json by 42% in PR #1874 (java-tracer)#1876

Merged
claude[bot] merged 1 commit intojava-tracerfrom
codeflash/optimize-pr1874-2026-03-19T08.11.52
Mar 19, 2026
Merged

⚡️ Speed up method JfrProfile._parse_json by 42% in PR #1874 (java-tracer)#1876
claude[bot] merged 1 commit intojava-tracerfrom
codeflash/optimize-pr1874-2026-03-19T08.11.52

Conversation

@codeflash-ai
Copy link
Contributor

@codeflash-ai codeflash-ai bot commented Mar 19, 2026

⚡️ This pull request contains optimizations for PR #1874

If you approve this dependent PR, these changes will be merged into the original PR branch java-tracer.

This PR will be automatically closed if the original PR is merged.


📄 42% (0.42x) speedup for JfrProfile._parse_json in codeflash/languages/java/jfr_parser.py

⏱️ Runtime : 46.4 milliseconds 32.6 milliseconds (best of 32 runs)

📝 Explanation and details

The optimization precomputes all frame-to-key conversions for a stack trace once (into a keys list) instead of calling _frame_to_key repeatedly inside the caller-callee loop, cutting per-frame extraction from ~3.3 µs to ~0.19 µs (83% reduction) and lifting _frame_to_key from 20.8% of total time to 43.2% (the loop cost is now dominated by the upfront list comprehension rather than repeated calls). A local matches_packages_cached closure memoizes package-filter results to avoid re-checking the same method keys across caller relationships, reducing _matches_packages overhead from 12.6% to 0.8% of total time; profiler data shows _matches_packages hits dropped from 18,364 to 1,500. The timestamp-duration calculation switched from accumulating a list then calling max()/min() to inline min/max tracking, removing intermediate allocations; combined, these changes yield a 42% overall speedup (46.4 ms → 32.6 ms).

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 91 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
import json  # used to build JSON test inputs

from codeflash.languages.java.jfr_parser import JfrProfile  # the class under test


def _make_profile_instance(packages=None):
    """Helper to create a real JfrProfile instance without invoking __init__.
    We use object.__new__ to avoid side effects in __init__ (like subprocess calls).
    We then initialize the attributes that _parse_json expects.
    """
    inst = object.__new__(JfrProfile)  # real instance, but __init__ is not executed
    # set package filters (empty list or provided)
    inst.packages = [] if packages is None else list(packages)
    # initialize internal state used by _parse_json
    inst._method_samples = {}
    inst._method_info = {}
    inst._caller_map = {}
    inst._recording_duration_ns = 0
    inst._total_samples = 0
    return inst


def test_parse_json_basic_single_event():
    inst = _make_profile_instance()

    frame = {"method": {"type": {"name": "com.example.Class"}, "name": "foo", "descriptor": "(I)V"}, "lineNumber": 42}
    events = []
    for ts in (100, 300):
        events.append({"type": "jdk.ExecutionSample", "values": {"stackTrace": {"frames": [frame]}, "startTime": ts}})
    payload = {"recording": {"events": events}}
    inst._parse_json(json.dumps(payload))  # 19.4μs -> 20.6μs (5.88% slower)

    assert inst._total_samples == 2
    key = "com.example.Class.foo"
    assert inst._method_samples.get(key) == 2
    assert key in inst._method_info
    assert inst._method_info[key]["class_name"] == "com.example.Class"
    assert inst._method_info[key]["method_name"] == "foo"
    assert inst._method_info[key]["descriptor"] == "(I)V"
    assert inst._method_info[key]["line_number"] == "42"
    assert inst._recording_duration_ns == 200


def test_non_executionsample_and_root_events_key_and_empty_frames():
    inst = _make_profile_instance()

    non_exec = {"type": "jdk.OtherEvent", "values": {"startTime": 100}}
    exec_empty_frames = {"type": "jdk.ExecutionSample", "values": {"stackTrace": {"frames": []}, "startTime": 200}}
    payload = {"events": [non_exec, exec_empty_frames]}
    inst._parse_json(json.dumps(payload))  # 10.7μs -> 10.5μs (1.72% faster)

    assert inst._total_samples == 1
    assert inst._method_samples == {}
    assert inst._method_info == {}
    assert inst._caller_map == {}
    assert inst._recording_duration_ns == 100


def test_frame_missing_method_fields():
    inst = _make_profile_instance()

    bad_frame = {"method": {"type": {"name": ""}, "name": ""}, "lineNumber": 0}
    good_frame = {"method": {"type": {"name": "com.example.Good"}, "name": "ok", "descriptor": "()V"}, "lineNumber": 1}
    event = {
        "type": "jdk.ExecutionSample",
        "values": {"stackTrace": {"frames": [bad_frame, good_frame]}, "startTime": 10},
    }
    payload = {"recording": {"events": [event, event]}}
    inst._parse_json(json.dumps(payload))  # 19.6μs -> 20.0μs (2.00% slower)

    assert inst._total_samples == 2
    assert inst._method_samples == {}
    assert inst._caller_map == {}
    assert inst._recording_duration_ns == 0


def test_matches_packages_filtering_and_caller_map_building():
    inst = _make_profile_instance(packages=["com.example"])

    callee_frame = {
        "method": {"type": {"name": "com.example.Service"}, "name": "work", "descriptor": "()V"},
        "lineNumber": 10,
    }
    caller_frame = {
        "method": {"type": {"name": "com.other.Util"}, "name": "helper", "descriptor": "()V"},
        "lineNumber": 20,
    }

    event1 = {
        "type": "jdk.ExecutionSample",
        "values": {"stackTrace": {"frames": [callee_frame, caller_frame]}, "startTime": 1000},
    }
    event2 = {
        "type": "jdk.ExecutionSample",
        "values": {"stackTrace": {"frames": [callee_frame, caller_frame]}, "startTime": 2000},
    }

    callee_frame_alt = {
        "method": {"type": {"name": "com.example.Controller"}, "name": "handle", "descriptor": "()V"},
        "lineNumber": 15,
    }
    caller_frame_alt = {
        "method": {"type": {"name": "com.lib.Framework"}, "name": "dispatch", "descriptor": "()V"},
        "lineNumber": 25,
    }

    event3 = {
        "type": "jdk.ExecutionSample",
        "values": {"stackTrace": {"frames": [callee_frame_alt, caller_frame_alt]}, "startTime": 3000},
    }

    inst._parse_json(json.dumps({"recording": {"events": [event1, event2, event3]}}))  # 34.3μs -> 32.9μs (4.33% faster)

    assert inst._total_samples == 3
    callee_key = "com.example.Service.work"
    assert inst._method_samples.get(callee_key) == 2
    assert inst._method_info[callee_key]["class_name"] == "com.example.Service"

    caller_key = "com.other.Util.helper"
    assert inst._caller_map[callee_key][caller_key] == 2

    callee_key_alt = "com.example.Controller.handle"
    assert inst._method_samples.get(callee_key_alt) == 1
    caller_key_alt = "com.lib.Framework.dispatch"
    assert inst._caller_map[callee_key_alt][caller_key_alt] == 1


def test_iso_timestamp_parsing_and_malformed_timestamps():
    # Verify that ISO timestamps are converted to epoch nanos and that malformed values are ignored.
    inst = _make_profile_instance()

    # two ISO timestamps exactly one second apart; include an invalid timestamp too
    iso1 = "2020-01-01T00:00:00Z"
    iso2 = "2020-01-01T00:00:01Z"
    valid_event1 = {
        "type": "jdk.ExecutionSample",
        "values": {"stackTrace": {"frames": [{"method": {"type": {"name": "com.X"}, "name": "m"}}]}, "startTime": iso1},
    }
    valid_event2 = {
        "type": "jdk.ExecutionSample",
        "values": {"stackTrace": {"frames": [{"method": {"type": {"name": "com.X"}, "name": "m"}}]}, "startTime": iso2},
    }
    bad_event = {
        "type": "jdk.ExecutionSample",
        "values": {
            "stackTrace": {"frames": [{"method": {"type": {"name": "com.X"}, "name": "m"}}]},
            "startTime": "not-a-timestamp",
        },
    }
    inst._parse_json(
        json.dumps({"recording": {"events": [valid_event1, bad_event, valid_event2]}})
    )  # 34.0μs -> 29.5μs (15.5% faster)

    # three events with non-empty frames => total_samples = 3
    assert inst._total_samples == 3
    # duration should be 1 second in nanoseconds = 1_000_000_000
    assert inst._recording_duration_ns == 1_000_000_000


def test_json_decode_error_and_empty_input_no_side_effects():
    # Passing invalid JSON should not raise and should leave internal state untouched.
    inst = _make_profile_instance()
    # record initial state
    before_totals = (
        dict(inst._method_samples),
        dict(inst._method_info),
        dict(inst._caller_map),
        inst._total_samples,
        inst._recording_duration_ns,
    )
    # invalid JSON
    inst._parse_json("this is not json")  # 491μs -> 487μs (0.871% faster)
    # state remains unchanged
    assert (
        inst._method_samples,
        inst._method_info,
        inst._caller_map,
        inst._total_samples,
        inst._recording_duration_ns,
    ) == before_totals


def test_large_scale_processing_of_many_events():
    inst = _make_profile_instance()

    events = []

    base_methods = [
        ("com.spring.web.Controller", "handleRequest"),
        ("com.spring.data.Repository", "findById"),
        ("com.spring.transaction.Manager", "commit"),
        ("com.google.guava.Cache", "get"),
        ("com.jackson.databind.Mapper", "readValue"),
        ("com.slf4j.Logger", "debug"),
        ("java.util.HashMap", "get"),
        ("java.io.BufferedReader", "readLine"),
    ]

    for i in range(50):
        method_idx = i % len(base_methods)
        f0_class, f0_method = base_methods[method_idx]
        f0 = {"method": {"type": {"name": f0_class}, "name": f0_method, "descriptor": "()V"}, "lineNumber": 10 + i}

        caller_idx = (i + 1) % len(base_methods)
        f1_class, f1_method = base_methods[caller_idx]
        f1 = {"method": {"type": {"name": f1_class}, "name": f1_method, "descriptor": "()V"}, "lineNumber": 20 + i}

        other_idx = (i + 2) % len(base_methods)
        f2_class, f2_method = base_methods[other_idx]
        f2 = {"method": {"type": {"name": f2_class}, "name": f2_method, "descriptor": "()V"}, "lineNumber": 30 + i}

        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {"stackTrace": {"frames": [f0, f1, f2]}, "startTime": i * 1000 + 500},
            }
        )

    for i in range(50, 100):
        method_idx = (i * 3) % len(base_methods)
        f0_class, f0_method = base_methods[method_idx]
        f0 = {"method": {"type": {"name": f0_class}, "name": f0_method, "descriptor": "(I)I"}, "lineNumber": 15 + i}

        caller_idx = (i * 5) % len(base_methods)
        f1_class, f1_method = base_methods[caller_idx]
        f1 = {
            "method": {"type": {"name": f1_class}, "name": f1_method, "descriptor": "(Ljava/lang/String;)V"},
            "lineNumber": 25 + i,
        }

        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {"stackTrace": {"frames": [f0, f1]}, "startTime": i * 2000 + 1500},
            }
        )

    inst._parse_json(json.dumps({"recording": {"events": events}}))  # 539μs -> 535μs (0.788% faster)

    assert inst._total_samples == 100
    total_counted = sum(inst._method_samples.values())
    assert total_counted == 100

    assert inst._method_samples, "expected some method samples to be recorded"

    for key in inst._method_samples.keys():
        if key in inst._caller_map:
            caller_total = sum(inst._caller_map[key].values())
            assert caller_total <= inst._method_samples[key]

    assert inst._recording_duration_ns > 0
import json
from pathlib import Path

# imports
from codeflash.languages.java.jfr_parser import JfrProfile


def test_parse_json_empty_string():
    """Test parsing JSON with no events array."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps({})
    jfr._parse_json(json_str)  # 4.76μs -> 5.21μs (8.66% slower)
    assert jfr._total_samples == 0
    assert len(jfr._method_samples) == 0


def test_parse_json_empty_object():
    """Test parsing a minimal valid JSON object with no events."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), [])
    jfr._parse_json("{}")  # 5.00μs -> 5.41μs (7.60% slower)
    # No events should result in no samples
    assert jfr._total_samples == 0
    assert jfr._method_samples == {}


def test_parse_json_single_execution_sample():
    """Test parsing a single valid ExecutionSample event."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "testMethod", "type": {"name": "com.example.TestClass"}},
                                    "lineNumber": 42,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 19.9μs -> 19.1μs (4.03% faster)
    # One sample should be recorded
    assert jfr._total_samples == 1
    assert jfr._method_samples["com.example.TestClass.testMethod"] == 1


def test_parse_json_nested_recording_structure():
    """Test parsing JSON with events nested under 'recording' key."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "recording": {
                "events": [
                    {
                        "type": "jdk.ExecutionSample",
                        "values": {
                            "stackTrace": {
                                "frames": [
                                    {
                                        "method": {"name": "nestedMethod", "type": {"name": "com.example.Nested"}},
                                        "lineNumber": 10,
                                    }
                                ]
                            },
                            "startTime": "2024-01-01T00:00:00Z",
                        },
                    }
                ]
            }
        }
    )
    jfr._parse_json(json_str)  # 19.3μs -> 18.7μs (3.54% faster)
    assert jfr._total_samples == 1
    assert "com.example.Nested.nestedMethod" in jfr._method_samples


def test_parse_json_ignores_non_execution_sample_events():
    """Test that non-ExecutionSample events are ignored."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {"type": "jdk.GarbageCollection", "values": {"stackTrace": {"frames": []}}},
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "goodMethod", "type": {"name": "com.example.Good"}},
                                    "lineNumber": 1,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 20.6μs -> 19.7μs (4.68% faster)
    # Only ExecutionSample should be counted
    assert jfr._total_samples == 1


def test_parse_json_package_filtering():
    """Test that package filtering works correctly."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "filteredMethod", "type": {"name": "org.other.Class"}},
                                    "lineNumber": 1,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 17.1μs -> 16.3μs (5.11% faster)
    # Method outside specified package should not be recorded
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 0


def test_parse_json_multiple_packages():
    """Test filtering with multiple package prefixes."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example", "org.test"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method1", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method2", "type": {"name": "org.test.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 27.8μs -> 25.5μs (9.13% faster)
    assert jfr._total_samples == 2
    assert len(jfr._method_samples) == 2


def test_parse_json_empty_packages_list_accepts_all():
    """Test that empty package list accepts all methods."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), [])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "anyMethod", "type": {"name": "any.package.Class"}},
                                    "lineNumber": 1,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 17.2μs -> 16.4μs (4.89% faster)
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 1


def test_parse_json_stores_method_info():
    """Test that method information is stored correctly."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {
                                        "name": "testMethod",
                                        "type": {"name": "com.example.TestClass"},
                                        "descriptor": "(Ljava/lang/String;)V",
                                    },
                                    "lineNumber": 123,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 19.5μs -> 18.7μs (4.34% faster)
    # Check stored method info
    assert "com.example.TestClass.testMethod" in jfr._method_info
    info = jfr._method_info["com.example.TestClass.testMethod"]
    assert info["class_name"] == "com.example.TestClass"
    assert info["method_name"] == "testMethod"
    assert info["descriptor"] == "(Ljava/lang/String;)V"
    assert info["line_number"] == "123"


def test_parse_json_caller_callee_relationship():
    """Test that caller-callee relationships are tracked."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "childMethod", "type": {"name": "com.example.Child"}},
                                    "lineNumber": 1,
                                },
                                {
                                    "method": {"name": "parentMethod", "type": {"name": "com.example.Parent"}},
                                    "lineNumber": 1,
                                },
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 22.1μs -> 20.5μs (7.78% faster)
    # Check caller map
    assert "com.example.Child.childMethod" in jfr._caller_map
    callers = jfr._caller_map["com.example.Child.childMethod"]
    assert "com.example.Parent.parentMethod" in callers
    assert callers["com.example.Parent.parentMethod"] == 1


def test_parse_json_multiple_callers():
    """Test tracking multiple callers for the same method."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "targetMethod", "type": {"name": "com.example.Target"}},
                                    "lineNumber": 1,
                                },
                                {"method": {"name": "caller1", "type": {"name": "com.example.A"}}, "lineNumber": 1},
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "targetMethod", "type": {"name": "com.example.Target"}},
                                    "lineNumber": 1,
                                },
                                {"method": {"name": "caller2", "type": {"name": "com.example.B"}}, "lineNumber": 1},
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 32.0μs -> 28.3μs (13.4% faster)
    callers = jfr._caller_map["com.example.Target.targetMethod"]
    assert len(callers) == 2
    assert callers["com.example.A.caller1"] == 1
    assert callers["com.example.B.caller2"] == 1


def test_parse_json_recording_duration_iso_format():
    """Test that recording duration is calculated from ISO format timestamps."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:10Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 26.6μs -> 24.0μs (10.8% faster)
    # Duration should be ~10 seconds in nanoseconds
    assert jfr._recording_duration_ns > 0
    assert jfr._recording_duration_ns >= 10_000_000_000


def test_parse_json_recording_duration_numeric_format():
    """Test that recording duration works with numeric nanosecond timestamps."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    base_time = 1704067200000000000  # arbitrary large timestamp in nanos
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": base_time,
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": base_time + 5_000_000_000,
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 20.2μs -> 20.9μs (3.40% slower)
    # Duration should be 5 seconds in nanoseconds
    assert jfr._recording_duration_ns == 5_000_000_000


def test_parse_json_invalid_json_caught():
    """Test that invalid JSON is gracefully handled."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    valid_json = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "validMethod", "type": {"name": "com.example.Valid"}},
                                    "lineNumber": 1,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(valid_json)  # 19.1μs -> 18.0μs (6.00% faster)
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 1


def test_parse_json_missing_stack_trace():
    """Test handling of events with missing stackTrace."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps({"events": [{"type": "jdk.ExecutionSample", "values": {}}]})
    jfr._parse_json(json_str)  # 6.72μs -> 7.03μs (4.41% slower)
    # Should count sample but not record any method
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 0


def test_parse_json_empty_frames_list():
    """Test handling of events with empty frames list."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {"stackTrace": {"frames": []}, "startTime": "2024-01-01T00:00:00Z"},
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 13.2μs -> 11.6μs (14.3% faster)
    # Should not count sample with no frames
    assert jfr._total_samples == 0


def test_parse_json_missing_method_name():
    """Test handling of frames with missing method name."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [{"method": {"type": {"name": "com.example.Class"}}, "lineNumber": 1}]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 15.6μs -> 14.5μs (8.11% faster)
    # Should count total sample but not record method
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 0


def test_parse_json_missing_class_name():
    """Test handling of frames with missing class name."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {"frames": [{"method": {"name": "method"}, "lineNumber": 1}]},
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 15.1μs -> 14.5μs (4.21% faster)
    # Should count total sample but not record method
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 0


def test_parse_json_deeply_nested_stack():
    """Test parsing very deep call stacks."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    # Build a deep stack
    frames = []
    for i in range(100):
        frames.append({"method": {"name": f"method{i}", "type": {"name": "com.example.Class"}}, "lineNumber": i})
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {"stackTrace": {"frames": frames}, "startTime": "2024-01-01T00:00:00Z"},
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 220μs -> 207μs (6.14% faster)
    # Should handle deep stacks
    assert jfr._total_samples == 1
    # All frames should be recorded with their callers
    assert len(jfr._caller_map) == 99  # n-1 caller relationships


def test_parse_json_missing_start_time():
    """Test event with missing startTime by processing distinct event structures."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "methodA", "type": {"name": "com.example.ClassA"}}, "lineNumber": 1}
                            ]
                        }
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "methodB", "type": {"name": "com.example.ClassB"}}, "lineNumber": 2}
                            ]
                        }
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 17.9μs -> 20.0μs (10.2% slower)
    # Should still record the samples
    assert jfr._total_samples == 2
    assert len(jfr._method_samples) == 2
    # Recording duration should not be set
    assert jfr._recording_duration_ns == 0


def test_parse_json_invalid_iso_timestamp():
    """Test event with malformed ISO timestamp."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "not-a-valid-timestamp",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 20.3μs -> 19.4μs (4.23% faster)
    # Should handle gracefully
    assert jfr._total_samples == 1


def test_parse_json_timestamp_as_float():
    """Test timestamps provided as floats."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    base_time = 1704067200.5
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": base_time,
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": base_time + 1.5,
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 21.6μs -> 21.7μs (0.640% slower)
    # Should handle float timestamps
    assert jfr._recording_duration_ns >= 1


def test_parse_json_duplicate_method_samples():
    """Test that duplicate method samples are accumulated."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:01Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 27.0μs -> 24.0μs (12.3% faster)
    # Both samples should be accumulated for the same method
    assert jfr._method_samples["com.example.Class.method"] == 2


def test_parse_json_method_info_not_overwritten():
    """Test that method info is only stored once."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {
                                        "name": "method",
                                        "type": {"name": "com.example.Class"},
                                        "descriptor": "(I)V",
                                    },
                                    "lineNumber": 100,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {
                                        "name": "method",
                                        "type": {"name": "com.example.Class"},
                                        "descriptor": "(J)V",
                                    },
                                    "lineNumber": 200,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:01Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 27.1μs -> 24.6μs (10.2% faster)
    # First stored info should be preserved
    info = jfr._method_info["com.example.Class.method"]
    assert info["descriptor"] == "(I)V"
    assert info["line_number"] == "100"


def test_parse_json_missing_descriptor_in_method_info():
    """Test method info storage when descriptor is missing."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 50}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 19.2μs -> 18.2μs (5.46% faster)
    info = jfr._method_info["com.example.Class.method"]
    assert info["descriptor"] == ""


def test_parse_json_missing_line_number():
    """Test method info storage when line number is missing."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [{"method": {"name": "method", "type": {"name": "com.example.Class"}}}]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 18.8μs -> 17.6μs (6.89% faster)
    info = jfr._method_info["com.example.Class.method"]
    assert info["line_number"] == "0"


def test_parse_json_caller_accumulation():
    """Test that multiple calls between same caller/callee pair accumulate."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "callee", "type": {"name": "com.example.A"}}, "lineNumber": 1},
                                {"method": {"name": "caller", "type": {"name": "com.example.B"}}, "lineNumber": 1},
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "callee", "type": {"name": "com.example.A"}}, "lineNumber": 1},
                                {"method": {"name": "caller", "type": {"name": "com.example.B"}}, "lineNumber": 1},
                            ]
                        },
                        "startTime": "2024-01-01T00:00:01Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 31.9μs -> 27.9μs (14.5% faster)
    callers = jfr._caller_map["com.example.A.callee"]
    assert callers["com.example.B.caller"] == 2


def test_parse_json_null_values_in_fields():
    """Test handling of null values in optional fields."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {
                                        "name": "method",
                                        "type": {"name": "com.example.Class"},
                                        "descriptor": None,
                                    },
                                    "lineNumber": None,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 19.1μs -> 17.8μs (7.39% faster)
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 1


def test_parse_json_special_characters_in_class_names():
    """Test handling of special characters in method/class names."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "lambda$method$0", "type": {"name": "com.example.Class$Inner"}},
                                    "lineNumber": 1,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 18.9μs -> 17.9μs (5.59% faster)
    assert "com.example.Class$Inner.lambda$method$0" in jfr._method_samples


def test_parse_json_very_long_class_names():
    """Test handling of very long class names."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com"])
    long_class = "com." + ".".join([f"package{i}" for i in range(50)])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [{"method": {"name": "method", "type": {"name": long_class}}, "lineNumber": 1}]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 19.9μs -> 19.0μs (4.85% faster)
    assert jfr._total_samples == 1
    assert len(jfr._method_samples) == 1


def test_parse_json_package_prefix_boundary():
    """Test package matching at boundaries."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "method", "type": {"name": "com.examplexyz.Class"}},
                                    "lineNumber": 1,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 18.9μs -> 18.0μs (4.78% faster)
    # Should match because prefix matching
    assert len(jfr._method_samples) == 1


def test_parse_json_single_event_no_caller():
    """Test single frame with no caller information."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {
                                    "method": {"name": "rootMethod", "type": {"name": "com.example.Root"}},
                                    "lineNumber": 1,
                                }
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                }
            ]
        }
    )
    jfr._parse_json(json_str)  # 18.6μs -> 18.0μs (3.21% faster)
    # Root method should still be recorded
    assert jfr._method_samples["com.example.Root.rootMethod"] == 1
    # Should not have any callers
    assert "com.example.Root.rootMethod" not in jfr._caller_map


def test_parse_json_events_at_exact_one_second_apart():
    """Test recording duration calculation with exactly 1 second difference."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    json_str = json.dumps(
        {
            "events": [
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:00Z",
                    },
                },
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": "2024-01-01T00:00:01Z",
                    },
                },
            ]
        }
    )
    jfr._parse_json(json_str)  # 26.5μs -> 24.2μs (9.73% faster)
    # Should be approximately 1 second
    assert 900_000_000 < jfr._recording_duration_ns < 1_100_000_000


def test_parse_json_many_events():
    """Test parsing 1000 events."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    events = []
    for i in range(1000):
        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {
                    "stackTrace": {
                        "frames": [
                            {
                                "method": {"name": f"method{i % 10}", "type": {"name": f"com.example.Class{i % 20}"}},
                                "lineNumber": i,
                            }
                        ]
                    },
                    "startTime": "2024-01-01T00:00:00Z",
                },
            }
        )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 4.07ms -> 3.11ms (31.1% faster)
    # Should process all events
    assert jfr._total_samples == 1000
    # Should accumulate samples
    assert sum(jfr._method_samples.values()) == 1000


def test_parse_json_deep_call_stacks_many_events():
    """Test parsing 100 events with deep call stacks (50 frames each)."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    events = []
    for event_idx in range(100):
        frames = []
        for frame_idx in range(50):
            frames.append(
                {
                    "method": {"name": f"method{frame_idx}", "type": {"name": "com.example.Class"}},
                    "lineNumber": frame_idx,
                }
            )
        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {"stackTrace": {"frames": frames}, "startTime": "2024-01-01T00:00:00Z"},
            }
        )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 9.82ms -> 6.03ms (62.8% faster)
    # Should handle all events and stacks
    assert jfr._total_samples == 100
    # Should create many caller relationships
    assert len(jfr._caller_map) > 0


def test_parse_json_many_distinct_methods():
    """Test parsing with 500 distinct method names."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    events = []
    for i in range(500):
        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {
                    "stackTrace": {
                        "frames": [
                            {
                                "method": {"name": f"uniqueMethod{i}", "type": {"name": "com.example.Class"}},
                                "lineNumber": 1,
                            }
                        ]
                    },
                    "startTime": "2024-01-01T00:00:00Z",
                },
            }
        )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 2.24ms -> 2.09ms (7.28% faster)
    # Should record all distinct methods
    assert len(jfr._method_samples) == 500
    assert jfr._total_samples == 500


def test_parse_json_many_packages():
    """Test parsing with many package filters."""
    packages = [f"com.example.pkg{i}" for i in range(100)]
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), packages)
    events = []
    for i in range(100):
        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {
                    "stackTrace": {
                        "frames": [
                            {
                                "method": {"name": "method", "type": {"name": f"com.example.pkg{i}.Class"}},
                                "lineNumber": 1,
                            }
                        ]
                    },
                    "startTime": "2024-01-01T00:00:00Z",
                },
            }
        )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 515μs -> 487μs (5.83% faster)
    # Should match all packages
    assert len(jfr._method_samples) == 100


def test_parse_json_complex_caller_graph():
    """Test complex caller-callee relationships."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    events = []
    # Create a tree-like call graph: each level has multiple methods
    for level in range(5):
        for branch in range(10):
            frames = []
            for d in range(level + 1):
                frames.append(
                    {
                        "method": {"name": f"method_l{d}_b{branch}", "type": {"name": "com.example.Class"}},
                        "lineNumber": 1,
                    }
                )
            events.append(
                {
                    "type": "jdk.ExecutionSample",
                    "values": {"stackTrace": {"frames": frames}, "startTime": "2024-01-01T00:00:00Z"},
                }
            )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 440μs -> 342μs (28.6% faster)
    # Should build comprehensive caller map
    assert jfr._total_samples == 50
    assert len(jfr._caller_map) > 0


def test_parse_json_repeated_caller_accumulation():
    """Test accumulation of repeated caller pairs over 500 calls."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    events = []
    for i in range(500):
        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {
                    "stackTrace": {
                        "frames": [
                            {"method": {"name": "callee", "type": {"name": "com.example.A"}}, "lineNumber": 1},
                            {"method": {"name": "caller", "type": {"name": "com.example.B"}}, "lineNumber": 1},
                        ]
                    },
                    "startTime": "2024-01-01T00:00:00Z",
                },
            }
        )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 3.00ms -> 2.14ms (39.8% faster)
    # Should accumulate all calls
    callers = jfr._caller_map["com.example.A.callee"]
    assert callers["com.example.B.caller"] == 500


def test_parse_json_mixed_package_filtering_at_scale():
    """Test package filtering with 200 mixed matching/non-matching events."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    events = []
    for i in range(200):
        # Alternate between matching and non-matching packages
        pkg = "com.example.Class" if i % 2 == 0 else "org.other.Class"
        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {
                    "stackTrace": {
                        "frames": [{"method": {"name": f"method{i}", "type": {"name": pkg}}, "lineNumber": 1}]
                    },
                    "startTime": "2024-01-01T00:00:00Z",
                },
            }
        )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 854μs -> 789μs (8.20% faster)
    # Should only count matching packages
    assert len(jfr._method_samples) == 100
    assert jfr._total_samples == 200


def test_parse_json_large_json_structure():
    """Test parsing very large JSON response."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    # Create 1000 events with varied structure
    events = []
    for i in range(1000):
        frames = []
        for j in range(10):  # 10 frames per stack
            frames.append(
                {
                    "method": {
                        "name": f"method{j}",
                        "type": {"name": f"com.example.Class{i % 50}"},
                        "descriptor": f"(L{j};){j % 5}",
                    },
                    "lineNumber": (i + j) % 1000,
                }
            )
        events.append(
            {
                "type": "jdk.ExecutionSample",
                "values": {"stackTrace": {"frames": frames}, "startTime": "2024-01-01T00:00:00Z"},
            }
        )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 23.4ms -> 15.6ms (50.0% faster)
    # Should handle large scale
    assert jfr._total_samples == 1000
    assert len(jfr._method_samples) > 0
    assert len(jfr._method_info) > 0


def test_parse_json_timestamp_range_at_scale():
    """Test recording duration calculation with distinct time offsets."""
    jfr = JfrProfile(Path("/nonexistent/file.jfr"), ["com.example"])
    events = []
    base_time_ns = 1704067200_000_000_000
    time_offsets = [0, 20_000_000_000, 50_000_000_000, 100_000_000_000]
    for offset in time_offsets:
        for i in range(3):
            events.append(
                {
                    "type": "jdk.ExecutionSample",
                    "values": {
                        "stackTrace": {
                            "frames": [
                                {"method": {"name": "method", "type": {"name": "com.example.Class"}}, "lineNumber": 1}
                            ]
                        },
                        "startTime": base_time_ns + offset,
                    },
                }
            )
    json_str = json.dumps({"events": events})
    jfr._parse_json(json_str)  # 56.3μs -> 51.7μs (8.91% faster)
    # Should calculate duration close to 100 seconds
    assert 99_000_000_000 < jfr._recording_duration_ns < 101_000_000_000

To edit these changes git checkout codeflash/optimize-pr1874-2026-03-19T08.11.52 and push.

Codeflash Static Badge

The optimization precomputes all frame-to-key conversions for a stack trace once (into a `keys` list) instead of calling `_frame_to_key` repeatedly inside the caller-callee loop, cutting per-frame extraction from ~3.3 µs to ~0.19 µs (83% reduction) and lifting `_frame_to_key` from 20.8% of total time to 43.2% (the loop cost is now dominated by the upfront list comprehension rather than repeated calls). A local `matches_packages_cached` closure memoizes package-filter results to avoid re-checking the same method keys across caller relationships, reducing `_matches_packages` overhead from 12.6% to 0.8% of total time; profiler data shows `_matches_packages` hits dropped from 18,364 to 1,500. The timestamp-duration calculation switched from accumulating a list then calling `max()`/`min()` to inline min/max tracking, removing intermediate allocations; combined, these changes yield a 42% overall speedup (46.4 ms → 32.6 ms).
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Mar 19, 2026
@claude
Copy link
Contributor

claude bot commented Mar 19, 2026

CI failures are pre-existing on the base branch (not caused by this PR): unit-tests (all platforms) fail due to test_git_utils tests that test old language-filtering behavior — these will be fixed once PR #1878 merges. Leaving open for merge once base branch CI is fixed.

@claude claude bot merged commit 5402088 into java-tracer Mar 19, 2026
20 of 30 checks passed
@claude claude bot deleted the codeflash/optimize-pr1874-2026-03-19T08.11.52 branch March 19, 2026 18:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants