From 562d1092e2735fec3af68e158f062928de008c35 Mon Sep 17 00:00:00 2001 From: Dipesh Babu Date: Wed, 18 Nov 2026 00:20:01 -0500 Subject: [PATCH] Qualify repeated-tool recommendations with input and safety evidence --- CHANGELOG.md | 7 +++ agentloop/estimates.py | 14 +++++- agentloop/findings.py | 9 +++- agentloop/graph.py | 3 +- agentloop/parallelism.py | 63 ++++++++++++++++++++++++-- agentloop/patches.py | 18 +++++++- agentloop/rules.py | 16 +++++-- docs/PARALLELIZATION.md | 32 ++++++++++--- tests/fixtures/html/many.html | 36 +++++++-------- tests/test_parallelization_evidence.py | 43 ++++++++++++++++++ tests/test_patch_plan.py | 2 +- 11 files changed, 204 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23e73a4..637e257 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ trace, study, receipt, API and database schema versions. ## [Unreleased] +### Fixed + +- Repeated-tool findings now ask developers to investigate when only the tool + name repeats. Matching opaque input keys and declared read-only behavior can + support testing request-local reuse ahead of concurrency. Plans and estimates + identify which change the evidence supports. + ### Added - Guided comparisons show trace latency and runner wall time in the CLI, JSON, diff --git a/agentloop/estimates.py b/agentloop/estimates.py index 20887ff..5fca82a 100644 --- a/agentloop/estimates.py +++ b/agentloop/estimates.py @@ -8,6 +8,7 @@ from agentloop.costs import is_cost_evaluable from agentloop.markdown import markdown_code_span, markdown_text +from agentloop.parallelism import REUSE_FORMULA @dataclass(frozen=True) @@ -92,8 +93,18 @@ def estimate_snapshot(candidate: Any, report: dict[str, Any], nodes: list[Any]) affected = set(candidate.affected_nodes or []) durations = [node.duration_ms for node in nodes if node.node_id in affected] cost_status = report.get("cost_status", "complete") + estimator_id = candidate.rule_id + extra_inputs = {} + if candidate.rule_id == "parallelize_tools": + retained = (candidate.observations or {}).get("retained_span_id") + if retained is not None: + estimator_id = "request_local_tool_reuse" + spec = Estimator(REUSE_FORMULA, ()) + extra_inputs["retained_duration_ms"] = next( + node.duration_ms for node in nodes if node.node_id == retained + ) return { - "estimator_id": candidate.rule_id, + "estimator_id": estimator_id, "estimator_version": spec.version, "method": "heuristic", "confidence": candidate.confidence, @@ -110,6 +121,7 @@ def estimate_snapshot(candidate: Any, report: dict[str, Any], nodes: list[Any]) "repeated_context_ratio": report.get("repeated_context_ratio", 0.0), "cost_status": cost_status, "token_status": report.get("token_status", "unspecified"), + **extra_inputs, }, "assumptions": list(dict.fromkeys([*(candidate.assumptions or []), *spec.assumptions])), "unmodeled_metrics": (["latency"] if candidate.rule_id == "cache_context" else ["cost"]), diff --git a/agentloop/findings.py b/agentloop/findings.py index 6777d56..0ce8396 100644 --- a/agentloop/findings.py +++ b/agentloop/findings.py @@ -256,6 +256,13 @@ def _finding_from_card( ] semantic = (card.get("estimate") or {}).get("estimator_id") == "semantic_leaf_removal" observations = dict(card.get("observations", {})) + identity_title = title + if ( + finding_type == "parallelize_tools" + and observations.get("recommended_action") == "inspect_repetition" + ): + # The wording change preserves existing reviewed finding IDs. + identity_title = f"Parallelize repeated `{observations['tool_name']}` tool calls" if semantic: severity = "medium" if card.get("confidence") == "medium" else "low" evidence.extend( @@ -265,7 +272,7 @@ def _finding_from_card( return OptimizationFinding( finding_id=_stable_finding_id( finding_type, - title, + identity_title, affected_spans, context={ "investigation_id": observations.get("investigation_id"), diff --git a/agentloop/graph.py b/agentloop/graph.py index 95532d1..87fa892 100644 --- a/agentloop/graph.py +++ b/agentloop/graph.py @@ -290,9 +290,10 @@ def dependency_summary(self): and len(identities) == len(self.nodes), } - def parallelizable_groups(self) -> list[dict[str, Any]]: + def parallelizable_groups(self, *, consider_reuse: bool = False) -> list[dict[str, Any]]: return parallelization_candidates( self.nodes, + consider_reuse=consider_reuse, dependency_edges=( (edge.source, edge.target) for edge in self.edges diff --git a/agentloop/parallelism.py b/agentloop/parallelism.py index a25a85c..98b1cf9 100644 --- a/agentloop/parallelism.py +++ b/agentloop/parallelism.py @@ -10,8 +10,8 @@ from agentloop.workflow_types import stage_summary PARALLELISM_NOTICE = ( - "Repeated tool calls may be candidates for concurrent execution. " - "Verify output independence and shared-state safety before changing them." + "The tool name repeats in the same scope. Compare inputs and check dependencies " + "and shared state before changing the calls." ) PARALLELISM_REWRITE = ( "After verifying output independence and shared-state safety, use asyncio.gather " @@ -20,6 +20,16 @@ PARALLELISM_FORMULA = ( "sum(tool durations) - max(tool duration), assuming the calls can run concurrently" ) +REUSE_REWRITE = ( + "Test reusing the first result within the same request. Confirm that the key covers " + "all effective inputs, the source stays stable, and task checks still pass." +) +REUSE_FORMULA = "sum_duration_ms - retained_duration_ms" +_REUSE_ASSUMPTIONS = ( + "The declared key covers all effective inputs and the source stays stable within the request.", + "Reused results preserve required behavior and add negligible overhead.", + "The skipped calls are on the runtime-limiting path.", +) _ASSUMPTIONS = ( "No call consumes another call's output.", "Calls do not conflict through shared mutable state.", @@ -28,7 +38,10 @@ def parallelization_candidates( - events: Iterable[Any], *, dependency_edges: Iterable[tuple[str, str]] = () + events: Iterable[Any], + *, + dependency_edges: Iterable[tuple[str, str]] = (), + consider_reuse: bool = False, ) -> list[dict[str, Any]]: """Return hypotheses, never proof of independence or verified savings. @@ -42,6 +55,7 @@ def parallelization_candidates( invalid_dependencies: set[str] = set() unsafe: set[str] = set() declarations: set[str] = set() + reuse_keys: dict[str, str] = {} for index, event in enumerate(events): span_id = ( getattr(event, "event_id", None) or getattr(event, "node_id", None) or f"node_{index}" @@ -70,6 +84,16 @@ def parallelization_candidates( unsafe.add(span_id) if operation_kind(event) == "tool": groups.setdefault((event.name, getattr(event, "parent_id", None)), []).append(span_id) + reuse_key = metadata.get("tool_reuse_key") + if ( + consider_reuse + and metadata.get("read_only") is True + and getattr(event, "status", None) == "ok" + and isinstance(reuse_key, str) + and 0 < len(reuse_key) <= 128 + and reuse_key == reuse_key.strip() + ): + reuse_keys[span_id] = reuse_key for span_id, event in by_id.items(): parent_id = getattr(event, "parent_id", None) if parent_id in by_id: @@ -106,6 +130,35 @@ def parallelization_candidates( sequential, parallel = sum(durations), max(durations) if sequential <= parallel: continue + keys = [reuse_keys.get(span_id) for span_id in span_ids] + if complete_timing and keys[0] is not None and all(key == keys[0] for key in keys): + retained = min(range(len(intervals)), key=intervals.__getitem__) + candidates.append( + { + "name": name, + "event_type": "tool_call", + "count": len(span_ids), + "node_ids": sorted(span_ids), + "sequential_time_ms": round(sequential, 3), + "estimated_savings_ms": round(sequential - durations[retained], 3), + "evidence_level": "declared", + "confidence": "medium", + "assumptions": list(_REUSE_ASSUMPTIONS), + "observations": { + "evidence_level": "observed", + "tool_call_count": len(span_ids), + "cumulative_span_time_ms": round(sequential, 3), + "timing": "non_overlapping", + "recommended_action": "test_request_local_reuse", + "same_input_key_declared": True, + "read_only_declared": True, + "retained_span_id": span_ids[retained], + }, + "description": "The integration declares matching input keys and read-only behavior for these successful calls.", + "estimate_formula": REUSE_FORMULA, + } + ) + continue declared = members <= declarations assumptions = list(_ASSUMPTIONS) if not complete_timing: @@ -127,6 +180,10 @@ def parallelization_candidates( "tool_call_count": len(span_ids), "cumulative_span_time_ms": round(sequential, 3), "timing": "non_overlapping" if complete_timing else "unavailable", + "tool_name": name, + "recommended_action": "test_parallelization" + if declared + else "inspect_repetition", }, "description": ( "The integration declares these calls safe to run concurrently; validate with replay." diff --git a/agentloop/patches.py b/agentloop/patches.py index 2b4f785..49a6157 100644 --- a/agentloop/patches.py +++ b/agentloop/patches.py @@ -237,7 +237,21 @@ def _plan_for_finding( evidence_names = _evidence_names(finding) files = _candidate_files(source_index, evidence_names) framework = _select_framework(frameworks, files) - templates = _rewrite_templates(finding_type, framework) + action = (finding.get("observations") or {}).get("recommended_action") + notes = _notes(finding_type, files) + if finding_type == "parallelize_tools" and action in { + "inspect_repetition", + "test_request_local_reuse", + }: + templates = { + "risk": "medium", + "before_pattern": str(finding.get("metadata", {}).get("why", "Repeated tool calls.")), + "proposed_rewrite": finding["rewrite"]["hint"], + "suggested_diff": "Change one behavior after reviewing the call inputs, then capture it again and verify the result with replay.", + } + notes = _notes("", files) + else: + templates = _rewrite_templates(finding_type, framework) return PatchPlan( patch_id=f"patch_{index:03d}", finding_id=str(finding["finding_id"]), @@ -255,7 +269,7 @@ def _plan_for_finding( finding.get("validation", {}).get("acceptance_criteria") or "before/after replay passes configured quality and budget gates" ), - notes=_notes(finding_type, files), + notes=notes, ) diff --git a/agentloop/rules.py b/agentloop/rules.py index acff258..c712b3a 100644 --- a/agentloop/rules.py +++ b/agentloop/rules.py @@ -11,7 +11,7 @@ from agentloop.costs import is_cost_evaluable from agentloop.estimates import ESTIMATORS, estimate_snapshot from agentloop.graph import ExecutionGraph -from agentloop.parallelism import PARALLELISM_REWRITE +from agentloop.parallelism import PARALLELISM_NOTICE, PARALLELISM_REWRITE, REUSE_REWRITE from agentloop.ranking import requirements from agentloop.tokens import UNAVAILABLE @@ -163,13 +163,19 @@ def run_rules( def _parallelization_cards(graph: ExecutionGraph) -> list[FindingCandidate]: cards = [] - for group in graph.parallelizable_groups(): + for group in graph.parallelizable_groups(consider_reuse=True): + action = group["observations"]["recommended_action"] + title, rewrite = { + "test_request_local_reuse": ("Test request-local reuse for", REUSE_REWRITE), + "test_parallelization": ("Parallelize repeated", PARALLELISM_REWRITE), + "inspect_repetition": ("Investigate repeated", PARALLELISM_NOTICE), + }[action] cards.append( FindingCandidate( type=RecommendationType.PARALLELIZE_TOOLS, - title=f"Parallelize repeated `{group['name']}` tool calls", + title=f"{title} `{group['name']}` tool calls", why=f"{group['count']} repeated calls. {group['description']}", - rewrite_hint=PARALLELISM_REWRITE, + rewrite_hint=rewrite, confidence=group["confidence"], estimated_latency_savings_ms=group["estimated_savings_ms"], affected_nodes=group["node_ids"], @@ -383,7 +389,7 @@ def _semantic_cards(context, family): BUILTIN_RULES = ( - FindingRule("parallelize_tools", "1.1", lambda ctx: _parallelization_cards(ctx.graph)), + FindingRule("parallelize_tools", "1.2", lambda ctx: _parallelization_cards(ctx.graph)), FindingRule("cache_context", "1.1", lambda ctx: _context_cache_cards(ctx.report, ctx.graph)), FindingRule("add_schema_validation", "1.2", lambda ctx: _retry_cards(ctx.graph)), FindingRule("batch_model_calls", "1.2", lambda ctx: _batch_model_cards(ctx.graph)), diff --git a/docs/PARALLELIZATION.md b/docs/PARALLELIZATION.md index 4b596a6..aadd289 100644 --- a/docs/PARALLELIZATION.md +++ b/docs/PARALLELIZATION.md @@ -1,9 +1,10 @@ # Parallelization evidence -Three or more same-named tool calls in the same parent scope can suggest a -concurrency experiment. Names and ordering do not establish that their outputs -or shared state are independent. AgentLoop reports a candidate with explicit -assumptions and validates improvements through baseline/candidate replay. +Three or more same-named tool calls in the same parent scope are worth +investigating. The finding asks you to compare inputs and inspect dependencies +and shared state. When all calls declare concurrency safety, the plan suggests +testing concurrency. Matching read-only calls can instead qualify for a reuse +experiment. ## Evidence levels @@ -42,6 +43,21 @@ malformed dependency lists, and references to missing dependency spans exclude t affected group. Declarations cannot override these conflicts. Omit `parallel_safe` when safety is unknown; a declaration on only some calls leaves the group inferred. +## Identical read-only calls + +For an immutable request-scoped lookup, instrument each call with +`metadata.read_only: true` and the same opaque `metadata.tool_reuse_key`. Use a +nonempty string of at most 128 characters. The key must account for the effective +arguments, resource version, and execution context. Do not put raw arguments or +secrets in the key. Use distinct keys when the effective inputs differ. + +The canonical finding suggests testing request-local reuse when the whole group +shares one key and all calls succeeded with complete, non-overlapping timing. +Existing dependency and safety exclusions still apply. The estimate subtracts +the first call's duration from total tool time. Cache lookup overhead, source +stability, and task correctness still need verification with replay. Tool keys +are omitted from the finding. + ## Savings assumptions and limits The estimated parallel time is the maximum selected call duration. Estimated @@ -58,6 +74,8 @@ candidate and an additional assumption that the calls ran serially. The legacy `sequential_time_ms` field is the sum of span durations, not a claim that serial execution was measured. Estimated savings are hypotheses, not measured speedups. -Existing titles and finding IDs remain stable when the selected spans are unchanged. -Groups now excluded by dependency, scope, or timing evidence can become superseded -on explicit re-diagnosis under the existing finding lifecycle. +`parallelize_tools` remains the finding family. A clearer title for a name-only +investigation preserves the existing finding ID. A request-local reuse finding +has a distinct ID for the different proposed change. Dependency, scope, and +timing changes can supersede findings on an explicit re-diagnosis under the +existing lifecycle. diff --git a/tests/fixtures/html/many.html b/tests/fixtures/html/many.html index d752899..53aeeac 100644 --- a/tests/fixtures/html/many.html +++ b/tests/fixtures/html/many.html @@ -1191,12 +1191,12 @@

Longest recorded spans

Bottlenec "status": "ok" } ] -
inferred evidencelow confidence

Parallelize repeated `retrieve-repeat3` tool calls

3 repeated calls. Repeated tool calls may be candidates for concurrent execution. Verify output independence and shared-state safety before changing them.

Investigation priority
8
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
+
inferred evidencelow confidence

Investigate repeated `retrieve-repeat3` tool calls

3 repeated calls. The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.

Investigation priority
8
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
   "automatic_application_allowed": false,
   "components": {
     "confidence": {
       "kind": "declared",
-      "source_ref": "rule:parallelize_tools:1.1",
+      "source_ref": "rule:parallelize_tools:1.2",
       "value": "low"
     },
     "cost": {
@@ -1288,7 +1288,7 @@ 

Longest recorded spans

Bottlenec "validation_cost_usd", "validation_effort_minutes" ] -}
Finding ID
al_parallelize_tools_21b66313a1f3
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
After verifying output independence and shared-state safety, use asyncio.gather or ThreadPoolExecutor and validate the change with replay.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat3, evt_quickstart_02-repeat3, evt_quickstart_03-repeat3

Estimator, assumptions, and observed inputs
{
+}
Finding ID
al_parallelize_tools_21b66313a1f3
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat3, evt_quickstart_02-repeat3, evt_quickstart_03-repeat3

Estimator, assumptions, and observed inputs
{
   "assumptions": [
     "No call consumes another call's output.",
     "Calls do not conflict through shared mutable state.",
@@ -1349,12 +1349,12 @@ 

Longest recorded spans

Bottlenec "status": "ok" } ] -
inferred evidencelow confidence

Parallelize repeated `retrieve-repeat1` tool calls

3 repeated calls. Repeated tool calls may be candidates for concurrent execution. Verify output independence and shared-state safety before changing them.

Investigation priority
9
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
+
inferred evidencelow confidence

Investigate repeated `retrieve-repeat1` tool calls

3 repeated calls. The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.

Investigation priority
9
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
   "automatic_application_allowed": false,
   "components": {
     "confidence": {
       "kind": "declared",
-      "source_ref": "rule:parallelize_tools:1.1",
+      "source_ref": "rule:parallelize_tools:1.2",
       "value": "low"
     },
     "cost": {
@@ -1446,7 +1446,7 @@ 

Longest recorded spans

Bottlenec "validation_cost_usd", "validation_effort_minutes" ] -}
Finding ID
al_parallelize_tools_2c1a691fb06a
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
After verifying output independence and shared-state safety, use asyncio.gather or ThreadPoolExecutor and validate the change with replay.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat1, evt_quickstart_02-repeat1, evt_quickstart_03-repeat1

Estimator, assumptions, and observed inputs
{
+}
Finding ID
al_parallelize_tools_2c1a691fb06a
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat1, evt_quickstart_02-repeat1, evt_quickstart_03-repeat1

Estimator, assumptions, and observed inputs
{
   "assumptions": [
     "No call consumes another call's output.",
     "Calls do not conflict through shared mutable state.",
@@ -1507,12 +1507,12 @@ 

Longest recorded spans

Bottlenec "status": "ok" } ] -
inferred evidencelow confidence

Parallelize repeated `retrieve-repeat4` tool calls

3 repeated calls. Repeated tool calls may be candidates for concurrent execution. Verify output independence and shared-state safety before changing them.

Investigation priority
10
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
+
inferred evidencelow confidence

Investigate repeated `retrieve-repeat4` tool calls

3 repeated calls. The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.

Investigation priority
10
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
   "automatic_application_allowed": false,
   "components": {
     "confidence": {
       "kind": "declared",
-      "source_ref": "rule:parallelize_tools:1.1",
+      "source_ref": "rule:parallelize_tools:1.2",
       "value": "low"
     },
     "cost": {
@@ -1604,7 +1604,7 @@ 

Longest recorded spans

Bottlenec "validation_cost_usd", "validation_effort_minutes" ] -}
Finding ID
al_parallelize_tools_4daf13a58672
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
After verifying output independence and shared-state safety, use asyncio.gather or ThreadPoolExecutor and validate the change with replay.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat4, evt_quickstart_02-repeat4, evt_quickstart_03-repeat4

Estimator, assumptions, and observed inputs
{
+}
Finding ID
al_parallelize_tools_4daf13a58672
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat4, evt_quickstart_02-repeat4, evt_quickstart_03-repeat4

Estimator, assumptions, and observed inputs
{
   "assumptions": [
     "No call consumes another call's output.",
     "Calls do not conflict through shared mutable state.",
@@ -1665,12 +1665,12 @@ 

Longest recorded spans

Bottlenec "status": "ok" } ] -
inferred evidencelow confidence

Parallelize repeated `retrieve` tool calls

3 repeated calls. Repeated tool calls may be candidates for concurrent execution. Verify output independence and shared-state safety before changing them.

Investigation priority
11
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
+
inferred evidencelow confidence

Investigate repeated `retrieve` tool calls

3 repeated calls. The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.

Investigation priority
11
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
   "automatic_application_allowed": false,
   "components": {
     "confidence": {
       "kind": "declared",
-      "source_ref": "rule:parallelize_tools:1.1",
+      "source_ref": "rule:parallelize_tools:1.2",
       "value": "low"
     },
     "cost": {
@@ -1762,7 +1762,7 @@ 

Longest recorded spans

Bottlenec "validation_cost_usd", "validation_effort_minutes" ] -}
Finding ID
al_parallelize_tools_6a08b742dfb3
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
After verifying output independence and shared-state safety, use asyncio.gather or ThreadPoolExecutor and validate the change with replay.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01, evt_quickstart_02, evt_quickstart_03

Estimator, assumptions, and observed inputs
{
+}
Finding ID
al_parallelize_tools_6a08b742dfb3
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01, evt_quickstart_02, evt_quickstart_03

Estimator, assumptions, and observed inputs
{
   "assumptions": [
     "No call consumes another call's output.",
     "Calls do not conflict through shared mutable state.",
@@ -1823,12 +1823,12 @@ 

Longest recorded spans

Bottlenec "status": "ok" } ] -
inferred evidencelow confidence

Parallelize repeated `retrieve-repeat2` tool calls

3 repeated calls. Repeated tool calls may be candidates for concurrent execution. Verify output independence and shared-state safety before changing them.

Investigation priority
12
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
+
inferred evidencelow confidence

Investigate repeated `retrieve-repeat2` tool calls

3 repeated calls. The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.

Investigation priority
12
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
   "automatic_application_allowed": false,
   "components": {
     "confidence": {
       "kind": "declared",
-      "source_ref": "rule:parallelize_tools:1.1",
+      "source_ref": "rule:parallelize_tools:1.2",
       "value": "low"
     },
     "cost": {
@@ -1920,7 +1920,7 @@ 

Longest recorded spans

Bottlenec "validation_cost_usd", "validation_effort_minutes" ] -}
Finding ID
al_parallelize_tools_7d06d1a068ee
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
After verifying output independence and shared-state safety, use asyncio.gather or ThreadPoolExecutor and validate the change with replay.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat2, evt_quickstart_02-repeat2, evt_quickstart_03-repeat2

Estimator, assumptions, and observed inputs
{
+}
Finding ID
al_parallelize_tools_7d06d1a068ee
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat2, evt_quickstart_02-repeat2, evt_quickstart_03-repeat2

Estimator, assumptions, and observed inputs
{
   "assumptions": [
     "No call consumes another call's output.",
     "Calls do not conflict through shared mutable state.",
@@ -1981,12 +1981,12 @@ 

Longest recorded spans

Bottlenec "status": "ok" } ] -
inferred evidencelow confidence

Parallelize repeated `retrieve-repeat0` tool calls

3 repeated calls. Repeated tool calls may be candidates for concurrent execution. Verify output independence and shared-state safety before changing them.

Investigation priority
13
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
+
inferred evidencelow confidence

Investigate repeated `retrieve-repeat0` tool calls

3 repeated calls. The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.

Investigation priority
13
Test readiness
needs evidence or review
Why
confidence weak or unknown; cost opportunity unavailable; evidence weak or unknown; missing input:quality risk; missing input:reversible; missing input:validation cost usd; missing input:validation effort minutes
Ranking components, input references and ordering
{
   "automatic_application_allowed": false,
   "components": {
     "confidence": {
       "kind": "declared",
-      "source_ref": "rule:parallelize_tools:1.1",
+      "source_ref": "rule:parallelize_tools:1.2",
       "value": "low"
     },
     "cost": {
@@ -2078,7 +2078,7 @@ 

Longest recorded spans

Bottlenec "validation_cost_usd", "validation_effort_minutes" ] -}
Finding ID
al_parallelize_tools_8542ede550f6
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
After verifying output independence and shared-state safety, use asyncio.gather or ThreadPoolExecutor and validate the change with replay.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat0, evt_quickstart_02-repeat0, evt_quickstart_03-repeat0

Estimator, assumptions, and observed inputs
{
+}
Finding ID
al_parallelize_tools_8542ede550f6
Estimated latency savings
360.000 ms
Estimated cost savings
$0.0000
Proposed change
The tool name repeats in the same scope. Compare inputs and check dependencies and shared state before changing the calls.
Validation
runtime decreases while tool outputs remain equivalent

Evidence spans: evt_quickstart_01-repeat0, evt_quickstart_02-repeat0, evt_quickstart_03-repeat0

Estimator, assumptions, and observed inputs
{
   "assumptions": [
     "No call consumes another call's output.",
     "Calls do not conflict through shared mutable state.",
diff --git a/tests/test_parallelization_evidence.py b/tests/test_parallelization_evidence.py
index 0ee5eba..45b0964 100644
--- a/tests/test_parallelization_evidence.py
+++ b/tests/test_parallelization_evidence.py
@@ -8,6 +8,7 @@
 from agentloop.findings import build_diagnosis, diagnosis_to_markdown
 from agentloop.graph import ExecutionEdge, ExecutionGraph
 from agentloop.optimizer import build_optimization_plan
+from agentloop.patches import build_patch_plan
 from agentloop.plan_export import export_optimization_markdown
 from agentloop.tracer import AgentTrace
 
@@ -51,6 +52,48 @@ def test_repeated_names_are_inferred_candidates_with_explicit_assumptions():
     assert group["estimated_savings_ms"] == 200
     assert "serial and independent" not in card["why"]
     assert "appear independent" not in str(report["recommendations"])
+    assert card["title"] == "Investigate repeated `search` tool calls"
+    assert "Compare inputs" in card["rewrite_hint"]
+
+
+def test_declared_identical_read_only_work_prefers_request_local_reuse(tmp_path):
+    metadata = {"read_only": True, "tool_reuse_key": "opaque-test-key", "parallel_safe": True}
+    trace = _trace(intervals=[(100, 220), (0, 100), (220, 300)], metadata=[metadata] * 3)
+    card = trace.report()["finding_candidates"][0]
+    assert card["observations"]["recommended_action"] == "test_request_local_reuse"
+    assert card["observations"]["retained_span_id"] == "tool-1"
+    assert card["estimated_latency_savings_ms"] == 200
+    assert card["estimate"]["estimator_id"] == "request_local_tool_reuse"
+    assert card["estimate"]["inputs"]["retained_duration_ms"] == 100
+    assert card["estimate"]["formula"] == "sum_duration_ms - retained_duration_ms"
+    assert "opaque-test-key" not in str(card)
+    [patch] = build_patch_plan(trace, repo_path=tmp_path, allowed_root=tmp_path)["patch_plans"]
+    assert "reusing the first result" in patch["proposed_rewrite"]
+    assert "asyncio.gather" not in str(patch)
+
+
+@pytest.mark.parametrize(
+    "change",
+    [
+        {"read_only": False},
+        {"read_only": 1},
+        {"tool_reuse_key": "other"},
+        {"tool_reuse_key": " "},
+        {"tool_reuse_key": ["opaque"]},
+    ],
+)
+def test_uncertain_reuse_remains_an_investigation(change):
+    metadata = {"read_only": True, "tool_reuse_key": "opaque"}
+    trace = _trace(metadata=[metadata, metadata, {**metadata, **change}])
+    [card] = trace.report()["finding_candidates"]
+    assert card["observations"]["recommended_action"] == "inspect_repetition"
+
+
+def test_failed_call_does_not_support_result_reuse():
+    trace = _trace(metadata=[{"read_only": True, "tool_reuse_key": "opaque"}] * 3)
+    trace.events[0].status = "error"
+    [card] = trace.report()["finding_candidates"]
+    assert card["observations"]["recommended_action"] == "inspect_repetition"
 
 
 def test_declared_concurrency_safety_is_distinct_from_verified_evidence():
diff --git a/tests/test_patch_plan.py b/tests/test_patch_plan.py
index 756ff33..8af2d54 100644
--- a/tests/test_patch_plan.py
+++ b/tests/test_patch_plan.py
@@ -26,7 +26,7 @@ def plan():
 
     with trace_agent("patchable") as trace:
         for _ in range(3):
-            with trace_tool_call("read_source"):
+            with trace_tool_call("read_source", metadata={"parallel_safe": True}):
                 pass
         repeated = "same stable instruction " * 100
         with trace_model_call("plan", input_text=repeated, output_tokens=1):