Commit graph

6373 commits

Author SHA1 Message Date
Kevin Turcios
0f5d578d37
Merge branch 'main' into ranker-multidim-scoring 2026-01-29 22:45:18 +00:00
Kevin Turcios
2aab251e8d
Merge branch 'main' into add/close_pr_end_point 2026-01-29 22:44:52 +00:00
HeshamHM28
c24f350719
Fix Prevent log code for paid org in the optimization feature "AI service " (#2325)
Fixes Cf-1038
2026-01-29 19:28:30 +00:00
HeshamHM28
1e8010c1ce fix tests 2026-01-29 18:40:45 +02:00
HeshamHM28
88b9265f92
Merge branch 'main' into add/close_pr_end_point 2026-01-29 08:37:59 -08:00
Kevin Turcios
04197195e8
Store instrumented performance tests in feature logging (#2330)
## Summary
- Add `instrumented_perf_test` field to `OptimizationFeatures` model
- Update `log_features` function to accept and store performance
instrumented tests

---------

Co-authored-by: Sarthak Agarwal <sarthak.saga@gmail.com>
2026-01-29 03:09:47 -05:00
aseembits93
f1b6fbf737 adding back the instructions 2026-01-28 16:13:28 -08:00
aseembits93
7386dd20b5 1-indexed ranking everywhere 2026-01-28 16:02:24 -08:00
aseembits93
71d397753d Merge remote-tracking branch 'origin/main' into ranker-multidim-scoring 2026-01-28 15:36:30 -08:00
aseembits93
215e6ad390 fixed merge issues 2026-01-28 15:33:11 -08:00
Saurabh Misra
8f7657da0d
Merge pull request #2247 from codeflash-ai/multi-language
codeflash-omni
2026-01-28 14:25:32 -08:00
ali
c19d9f4450
fix unit tests 2026-01-28 23:20:48 +02:00
ali
f0480fac39
use treesitter for validating js & ts code syntax 2026-01-28 23:15:30 +02:00
ali
db3f269b37
linting and formatting 2026-01-28 22:41:27 +02:00
ali
ec97ebd4e7
more cleanup 2026-01-28 22:23:54 +02:00
ali
31091350c9
cleanup 2026-01-28 22:19:40 +02:00
ali
dcac02b3f2
abstraction 2026-01-28 21:53:51 +02:00
ali
373d4c6574
Merge branch 'main' of github.com:codeflash-ai/codeflash-internal into multi-language 2026-01-28 20:47:57 +02:00
mashraf-222
d9a8aa8811
enhance LLM response view & adding ranker details in observability (#2326)
<img width="1755" height="1017" alt="image"
src="https://github.com/user-attachments/assets/9d398362-48b0-45b3-82a7-acf1174f1684"
/>
<img width="1901" height="1043" alt="image"
src="https://github.com/user-attachments/assets/a3ea7ef4-4b62-4f72-874e-80b28d513b8d"
/>

---------

Co-authored-by: Codeflash Bot <bot@codeflash.ai>
Co-authored-by: Kevin Turcios <106575910+KRRT7@users.noreply.github.com>
2026-01-28 13:20:00 -05:00
Sarthak Agarwal
a7b9333321
Merge branch 'main' into add/close_pr_end_point 2026-01-28 22:15:28 +05:30
HeshamHM28
f909642ce1
feat: Add Line Profiler visualization to webapp (#2268)
## Summary
Adds a line-by-line performance profiler visualization to the webapp,
allowing users to compare execution times between original and optimized
code.

  ## Changes

  ### New Line Profiler View
- **`LineProfilerView.tsx`**: Side-by-side comparison component showing:
    - Line-by-line execution times with heat map visualization
    - Syntax highlighting using `prism-react-renderer`
    - Collapsible function blocks
    - Light/dark mode support
    - Heat legend (cold → hot based on % time)

- **`lineProfilerParser.ts`**: Parser utilities for line profiler data:
- `parseLineProfilerResults()` - parses markdown table output from
Python's line_profiler
- `formatTime()` - converts timer units to human-readable format (ns,
µs, ms, s)
    - `getHeatLevel()` - determines heat coloring based on % time

- **`/review-optimizations/[traceId]/profiler/page.tsx`**: New route for
the profiler view

  ### API Changes
- **`create-pr.ts`**: Adds "📊 Performance Profile" link to PR
description when profiler data exists
- **`github-app.ts`**: Removes line profiler data from metadata when PR
is closed/merged
- **`create-staging.ts`**, **`suggest-pr-changes.ts`**: Handle line
profiler data in staging
- **`staging-storage-strategy.ts`**: Interface updates for line profiler
fields

  ### Webapp Integration
- **`page.tsx`**: Added "Performance Profile" button (only visible when
profiler data exists)
- **`action.ts`**: Sends line profiler data when creating PR from webapp
  Fixes CF-1018
  


https://codeflash-ai.slack.com/files/U08MSR1UN6L/F0A9YVDJY75/screen_recording_2026-01-21_at_10.03.18___pm.mov
https://github.com/HeshamHM28/my-best-repo/pull/21

linked to https://github.com/codeflash-ai/codeflash/pull/1139

---------

Co-authored-by: Aseem Saxena <aseem.bits@gmail.com>
2026-01-28 08:36:54 -08:00
Kevin Turcios
5ab169076c
Merge branch 'main' into multi-language 2026-01-28 08:19:52 -05:00
Kevin Turcios
8a66c78220
refactor: consolidate CST utilities and simplify add_missing_imports (#2324)
## Summary
- Consolidate shared CST utilities into `aiservice/common/cst_utils.py`
- Simplify `add_missing_imports` by removing redundant abstractions
- Require CST modules instead of strings in postprocessing pipeline
2026-01-28 08:05:45 -05:00
ali
d7e7125220
Merge branch 'multi-language' of github.com:codeflash-ai/codeflash-internal into multi-language 2026-01-28 13:41:55 +02:00
ali
557fb11939
remove jest globals check (client handles it now) 2026-01-28 13:41:06 +02:00
Sarthak Agarwal
dd4510b254 new endpoint for close pr 2026-01-28 16:47:43 +05:30
misrasaurabh1
b0a1d6c09f Remove instrumentation of js tests from aiservice and into client 2026-01-27 16:10:35 -08:00
ali
39de6a3bce
Merge branch 'multi-language' of github.com:codeflash-ai/codeflash-internal into multi-language 2026-01-27 23:30:11 +02:00
ali
72cb589948
some instrumentation fixes 2026-01-27 23:30:03 +02:00
Aseem Saxena
7f8ce66c6a multi dimensional scoring and structured json parsing for ranker 2026-01-27 12:24:16 -08:00
mohammed ahmed
a517f76b3c
Merge branch 'multi-language' into codeflash/optimize-checkForValidAPIKey-mkwv868t 2026-01-27 19:45:44 +02:00
mohammed ahmed
0c9cc6afe4
Merge branch 'main' into multi-language 2026-01-27 19:44:57 +02:00
mohammed ahmed
3e3ad7d9d7
Merge branch 'main' into codeflash/optimize-checkForValidAPIKey-mkwv868t 2026-01-27 19:42:55 +02:00
codeflash-ai-dev[bot]
b3da3330d2
Optimize checkForValidAPIKey
The optimized code achieves a **30% runtime improvement** (765ms → 587ms) by replacing the regex-based Bearer token extraction with a more efficient string operation.

## Key Optimization

**Bearer Token Extraction (Line 45-48)**
- **Original**: `authHeader.replace(/^Bearer\s+/, "")` - Uses regex pattern matching on every request
- **Optimized**: `authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader` - Simple string prefix check and substring operation

## Why This Works

1. **Regex Overhead Elimination**: Regular expressions require pattern compilation and matching, which is computationally expensive compared to simple string operations. The `startsWith()` method performs a direct character comparison, while `substring(7)` is a simple offset-based extraction.

2. **Hot Path Impact**: This middleware runs on **every authenticated API request**, making it a critical hot path. The line profiler shows this operation consuming 4.1% of execution time in the original code (0.297ms across 53 hits). Even small per-request savings compound significantly under load.

3. **Maintained Correctness**: The optimization preserves the same behavior - extracting the token after "Bearer " prefix, or using the entire header value if the prefix is absent. The concurrent execution test (50 mixed valid/invalid requests) validates this works correctly at scale, showing 30.6% faster execution (762ms → 584ms).

## Test Case Performance

- **Basic authentication flow**: Benefits from reduced token extraction overhead on every successful auth
- **Concurrent requests** (50 mixed valid/invalid): Shows **30.6% improvement** (762ms → 584ms), demonstrating the optimization scales well under concurrent load
- **Edge cases** (missing headers, invalid keys, errors): Minimal impact since they bypass the optimized path, but still benefit from overall reduced latency

**Note**: The code also removes a redundant `userId == null` check (original line 65-87) that was unreachable after the earlier null check, further reducing unnecessary conditional branches.
2026-01-27 17:24:53 +00:00
snyk-io[bot]
f7f3e7f0bd
[Snyk] Security upgrade diff from 8.0.2 to 8.0.3 (#2305)
![snyk-top-banner](https://res.cloudinary.com/snyk/image/upload/r-d/scm-platform/snyk-pull-requests/pr-banner-default.svg)

### Snyk has created this PR to fix 1 vulnerabilities in the npm
dependencies of this project.

#### Snyk changed the following file(s):

- `js/VSC-Extension/package.json`




#### Vulnerabilities that will be fixed with an upgrade:

|  | Issue | Score | 

:-------------------------:|:-------------------------|:-------------------------
![medium
severity](https://res.cloudinary.com/snyk/image/upload/w_20,h_20/v1561977819/icon/m.png
'medium severity') | Regular Expression Denial of Service (ReDoS)
<br/>[SNYK-JS-DIFF-14917201](https://snyk.io/vuln/SNYK-JS-DIFF-14917201)
| &nbsp;&nbsp;**708**&nbsp;&nbsp;




---

> [!IMPORTANT]
>
> - Check the changes in this PR to ensure they won't cause issues with
your project.
> - Max score is 1000. Note that the real score may have changed since
the PR was raised.
> - This PR was automatically created by Snyk using the credentials of a
real user.

---

**Note:** _You are seeing this because you or someone else with access
to this repository has authorized Snyk to open fix PRs._

For more information: <img
src="https://api.segment.io/v1/pixel/track?data=eyJ3cml0ZUtleSI6InJyWmxZcEdHY2RyTHZsb0lYd0dUcVg4WkFRTnNCOUEwIiwiYW5vbnltb3VzSWQiOiI1YmZkM2I3OC1iNmQ1LTRmNTYtODBhNC1iZDg4YmMzMTA4NDAiLCJldmVudCI6IlBSIHZpZXdlZCIsInByb3BlcnRpZXMiOnsicHJJZCI6IjViZmQzYjc4LWI2ZDUtNGY1Ni04MGE0LWJkODhiYzMxMDg0MCJ9fQ=="
width="0" height="0"/>
🧐 [View latest project
report](https://app.snyk.io/org/sarthak-aNe3RTvxtiDtBRn3AkWpLk/project/9d3b7f4a-fb81-42ff-ac9e-3cf1a6bff233?utm_source&#x3D;github-cloud-app&amp;utm_medium&#x3D;referral&amp;page&#x3D;fix-pr)
📜 [Customise PR
templates](https://docs.snyk.io/scan-using-snyk/pull-requests/snyk-fix-pull-or-merge-requests/customize-pr-templates?utm_source=github-cloud-app&utm_content=fix-pr-template)
🛠 [Adjust project
settings](https://app.snyk.io/org/sarthak-aNe3RTvxtiDtBRn3AkWpLk/project/9d3b7f4a-fb81-42ff-ac9e-3cf1a6bff233?utm_source&#x3D;github-cloud-app&amp;utm_medium&#x3D;referral&amp;page&#x3D;fix-pr/settings)
📚 [Read about Snyk's upgrade
logic](https://docs.snyk.io/scan-with-snyk/snyk-open-source/manage-vulnerabilities/upgrade-package-versions-to-fix-vulnerabilities?utm_source=github-cloud-app&utm_content=fix-pr-template)

---

**Learn how to fix vulnerabilities with free interactive lessons:**

🦉 [Regular Expression Denial of Service
(ReDoS)](https://learn.snyk.io/lesson/redos/?loc&#x3D;fix-pr)

[//]: #
'snyk:metadata:{"breakingChangeRiskLevel":null,"FF_showPullRequestBreakingChanges":false,"FF_showPullRequestBreakingChangesWebSearch":false,"customTemplate":{"variablesUsed":[],"fieldsUsed":[]},"dependencies":[{"name":"diff","from":"8.0.2","to":"8.0.3"}],"env":"prod","issuesToFix":["SNYK-JS-DIFF-14917201"],"prId":"5bfd3b78-b6d5-4f56-80a4-bd88bc310840","prPublicId":"5bfd3b78-b6d5-4f56-80a4-bd88bc310840","packageManager":"npm","priorityScoreList":[708],"projectPublicId":"9d3b7f4a-fb81-42ff-ac9e-3cf1a6bff233","projectUrl":"https://app.snyk.io/org/sarthak-aNe3RTvxtiDtBRn3AkWpLk/project/9d3b7f4a-fb81-42ff-ac9e-3cf1a6bff233?utm_source=github-cloud-app&utm_medium=referral&page=fix-pr","prType":"fix","templateFieldSources":{"branchName":"default","commitMessage":"default","description":"default","title":"default"},"templateVariants":["updated-fix-title","priorityScore"],"type":"auto","upgrade":["SNYK-JS-DIFF-14917201"],"vulns":["SNYK-JS-DIFF-14917201"],"patch":[],"isBreakingChange":false,"remediationStrategy":"vuln"}'

Co-authored-by: snyk-io[bot] <141718529+snyk-io[bot]@users.noreply.github.com>
2026-01-27 17:37:39 +05:30
Sarthak Agarwal
ccdebe5782
fix for cf-api route issue and process exit (#2315) 2026-01-27 17:35:48 +05:30
Kevin Turcios
1b2105e6d3
Merge branch 'main' into multi-language 2026-01-27 01:25:52 -05:00
Kevin Turcios
3fabea495f fix: install uv in fix-formatting workflow
The ty-check hook requires uv to be available. Add astral-sh/setup-uv
step before running prek.
2026-01-27 01:25:19 -05:00
Kevin Turcios
bf3890fdbf fix: use interactive mode for Claude @mentions
Remove prompt parameter from claude-mention job so Claude runs in
interactive mode and naturally receives @mention context. Move prek
formatting instructions to CLAUDE.md where Claude reads them for any
request.
2026-01-27 01:24:07 -05:00
Kevin Turcios
d26871b355
Merge branch 'main' into multi-language 2026-01-27 01:18:25 -05:00
Kevin Turcios
d80321da9f one more cc debug 2026-01-27 01:17:48 -05:00
Kevin Turcios
35e5e37f7e
Merge branch 'main' into multi-language 2026-01-27 01:08:17 -05:00
Kevin Turcios
a741523b1f debug
- Add standalone fix-formatting.yml workflow for `/fix-formatting` command
- Uses prek's native --from-ref to only format changed files
- Properly handles prek exit codes and reports errors
- Enable show_full_output in claude-mention job for debugging
2026-01-27 01:07:55 -05:00
Kevin Turcios
646a480769
Merge branch 'main' into multi-language 2026-01-27 00:57:23 -05:00
Kevin Turcios
f558f882bb Create fix-formatting.yml 2026-01-27 00:55:25 -05:00
Kevin Turcios
a22672d504 fix: improve Claude Code prompt for prek formatting fixes
Update the prompt to explicitly mention "pre-k" and "prek" triggers
and provide step-by-step instructions for running the formatter,
committing, and pushing changes.
2026-01-27 00:51:59 -05:00
Kevin Turcios
e464bcaae2
Merge branch 'main' into multi-language 2026-01-27 00:44:56 -05:00
Kevin Turcios
98b6577bc8 one more fix for CC 2026-01-27 00:43:52 -05:00
Kevin Turcios
e141c7e4fd
Merge branch 'main' into multi-language 2026-01-27 00:32:09 -05:00
codeflash-ai[bot]
238de2b9c0
️ Speed up function _safe_replace_function_calls by 101% in PR #2247 (multi-language) (#2306)
## ️ This pull request contains optimizations for PR #2247
If you approve this dependent PR, these changes will be merged into the
original PR branch `multi-language`.
>This PR will be automatically closed if the original PR is merged.
----
#### 📄 101% (1.01x) speedup for ***`_safe_replace_function_calls` in
`django/aiservice/testgen/instrumentation/javascript/instrument_javascript.py`***

⏱️ Runtime : **`4.63 milliseconds`** **→** **`2.30 milliseconds`** (best
of `5` runs)

#### 📝 Explanation and details


This optimization achieves a **101% speedup** (reducing runtime from
4.63ms to 2.30ms) through three key performance improvements:

**1. Pre-compiled regex pattern (primary speedup driver)**
The original code calls `re.match(pattern, remaining)` inside the main
loop, which recompiles the pattern on every iteration. The line profiler
shows this operation took 3.92 seconds (33.1% of total time). The
optimized version compiles the pattern once upfront (`pattern_re =
re.compile(pattern)`) and reuses it via `pattern_re.match(source, i)`,
reducing this to 1.10 seconds (10% of total time) - a **72% reduction**
in pattern matching overhead.

**2. Eliminated substring creation for pattern matching**
The original creates a new substring `remaining = source[i:]` on every
loop iteration (5.68e8 ns, 4.8% of time). The optimized version uses
`pattern_re.match(source, i)` which matches directly from position `i`
without creating intermediate strings. This saves both allocation and
copying costs, particularly impactful given the loop runs 1.3-1.8
million times per execution.

**3. Fast-forward through comments using `str.find()`**
- **Single-line comments**: Changed from character-by-character loop
(`while i < length and source[i] != "\n"`) to `source.find("\n", i)`,
eliminating repeated indexing operations
- **Multi-line comments**: Changed from character-by-character scanning
to `source.find("*/", i)`, directly jumping to comment end

**Test case analysis:**
The optimization particularly excels on:
- **Large-scale scenarios**: The 500-iteration test shows 125% speedup
(1.24ms → 549μs), demonstrating excellent scalability
- **Comment-heavy code**: Tests with comments show 17-65% speedups as
`str.find()` efficiently skips entire comment blocks
- **Method call filtering**: Tests with `.foo()` patterns show 53-75%
speedups from reduced pattern matching overhead

All 45 test cases pass with improved or comparable performance,
validating that the optimization preserves correctness while delivering
consistent runtime improvements across diverse JavaScript code patterns.



 **Correctness verification report:**

| Test                        | Status            |
| --------------------------- | ----------------- |
| ⚙️ Existing Unit Tests | 🔘 **None Found** |
| 🌀 Generated Regression Tests |  **59 Passed** |
|  Replay Tests | 🔘 **None Found** |
| 🔎 Concolic Coverage Tests | 🔘 **None Found** |
|📊 Tests Coverage       | 100.0% |
<details>
<summary>🌀 Click to see Generated Regression Tests</summary>

```python
from __future__ import annotations

# imports
import re
from collections.abc import Callable

import pytest  # used for our unit tests

from testgen.instrumentation.javascript.instrument_javascript import (
    _safe_replace_function_calls,
)

# unit tests


# Helper replacement function used in many tests: wraps the matched call
def _wrap_with_capture(match: re.Match[str]) -> str:
    # return a wrapper that includes the exact matched text
    return f"codeflash.capture({match.group(0)})"


def test_basic_single_replacement():
    # Basic scenario: a single top-level function call should be replaced.
    src = "var x = foo(1);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 12.5μs -> 9.73μs (28.9% faster)


def test_string_literals_not_replaced():
    # Strings containing the function call should be left alone.
    src = "var s = 'foo(1)'; foo(2);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 14.5μs -> 10.5μs (38.5% faster)


def test_double_quoted_and_escaped_strings():
    # Double-quoted strings with escaped quotes should be preserved.
    src = 'var s = "he said \\"foo(3)\\""; foo(4);'
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 15.7μs -> 11.5μs (36.0% faster)


def test_template_literals_with_expressions_skipped():
    # Template literals should preserve content and skip replacement inside ${...}.
    src = "`start ${ { nested: foo(5) } } end` foo(6);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 12.8μs -> 12.0μs (6.23% faster)


def test_single_line_comment_skipped():
    # Calls inside single-line comments should not be replaced.
    src = " // foo(7)\nfoo(8);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 9.40μs -> 8.02μs (17.1% faster)


def test_multi_line_comment_skipped_and_unclosed_comment_handled():
    # Multi-line comments containing calls should be preserved.
    src = "/* comment foo(9) */ foo(10);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 9.87μs -> 8.17μs (20.9% faster)

    # Unclosed multi-line comment at EOF should not hang or replace inside it
    src_unclosed = "/* unclosed foo(11)"
    codeflash_output = _safe_replace_function_calls(
        src_unclosed, "foo", _wrap_with_capture, pattern
    )
    res_unclosed = codeflash_output  # 3.26μs -> 1.97μs (65.2% faster)


def test_method_call_dot_not_replaced():
    # Calls that are methods (preceded by a dot) should not be replaced.
    src = "obj.foo(12); foo(13);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 14.8μs -> 9.49μs (55.6% faster)


def test_already_wrapped_skipped():
    # If 'codeflash.capture' immediately precedes the call start index, replacement should be skipped.
    # This tests the specific check in the function that avoids double-wrapping.
    src = "codeflash.capturefoo(14);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 19.9μs -> 11.3μs (75.4% faster)


def test_template_literal_with_escaped_backticks_and_expressions():
    # Template literal containing escaped backticks and ${...} should be handled correctly.
    src = r"`backtick \` and ${ { foo: foo(15) } } end` foo(16);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 14.2μs -> 12.8μs (11.1% faster)


def test_overlapping_names_handling():
    # When function name appears adjacent to other letters like 'foofoo(17)',
    # ensure inner call is still found at the correct position.
    src = "foofoo(17); foo(18);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 11.3μs -> 7.92μs (43.2% faster)


def test_escaped_characters_in_regular_strings_do_not_break_scanning():
    # Strings that include escaped backslashes and escaped quotes should not break the scanner.
    src = '"line1\\nfoo(19)\\nline2" foo(20);'
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 10.9μs -> 9.15μs (19.1% faster)


def test_large_scale_multiple_replacements():
    # Large-scale test: many occurrences (but below 1000) to assess scalability.
    count = 500  # keep below 1000 as per instructions
    src_parts = [f"foo({i});" for i in range(count)]
    src = " ".join(src_parts)
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 1.24ms -> 549μs (125% faster)
    # Ensure that every occurrence was wrapped exactly once.
    wrapped_count = res.count("codeflash.capture(")


def test_no_false_positive_when_preceded_by_other_chars():
    # If the character before the function is not a dot but some other char, replacement should proceed.
    src = "afoo(21); .foo(22);"
    pattern = r"foo\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 13.3μs -> 8.96μs (48.5% faster)


def test_pattern_that_matches_functions_with_spaces():
    # Pattern that allows spaces before the opening parenthesis.
    src = "foo (23); foo(24);"
    pattern = r"foo\s*\([^\)]*\)"
    codeflash_output = _safe_replace_function_calls(
        src, "foo", _wrap_with_capture, pattern
    )
    res = codeflash_output  # 10.1μs -> 7.71μs (30.6% faster)


# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

```

```python
import re
from collections.abc import Callable

# imports
import pytest

from testgen.instrumentation.javascript.instrument_javascript import (
    _safe_replace_function_calls,
)


class TestBasicFunctionality:
    """Test cases for basic functionality of _safe_replace_function_calls."""

    def test_simple_function_call_replacement(self):
        """Test replacing a simple function call with a basic pattern."""
        source = "foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 5.38μs -> 5.00μs (7.58% faster)

    def test_function_call_with_arguments(self):
        """Test replacing function calls that have arguments."""
        source = "foo(x, y)"
        pattern = r"foo\([^)]*\)"
        replace_func = lambda m: "bar(x, y)"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 5.25μs -> 4.74μs (10.7% faster)

    def test_multiple_function_calls(self):
        """Test replacing multiple occurrences of the same function."""
        source = "foo(); foo(); foo();"
        pattern = r"foo\(\)"
        call_count = [0]

        def replace_func(m):
            call_count[0] += 1
            return f"replaced_{call_count[0]}()"

        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 12.2μs -> 8.70μs (40.3% faster)

    def test_empty_source(self):
        """Test with an empty source string."""
        source = ""
        pattern = r"foo\(\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 853ns -> 2.04μs (58.1% slower)

    def test_no_matches(self):
        """Test when no function calls match the pattern."""
        source = "let x = 5; y = 10;"
        pattern = r"foo\(\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 14.3μs -> 7.73μs (84.8% faster)

    def test_function_call_in_middle_of_code(self):
        """Test replacing function call in the middle of other code."""
        source = "let result = foo(); console.log(result);"
        pattern = r"foo\(\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 24.9μs -> 12.9μs (92.5% faster)

    def test_preserve_whitespace(self):
        """Test that whitespace around function calls is preserved."""
        source = "foo(  )  "
        pattern = r"foo\(\s*\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 6.61μs -> 5.85μs (12.8% faster)

    def test_function_call_in_single_quoted_string(self):
        """Test that function calls inside single-quoted strings are NOT replaced."""
        source = "'foo()' bar()"
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 7.49μs -> 7.27μs (3.07% faster)

    def test_function_call_in_double_quoted_string(self):
        """Test that function calls inside double-quoted strings are NOT replaced."""
        source = '"foo()" bar()'
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 7.22μs -> 6.47μs (11.5% faster)

    def test_function_call_in_single_line_comment(self):
        """Test that function calls in single-line comments are NOT replaced."""
        source = "// foo() should not be replaced\nbar()"
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 9.27μs -> 6.86μs (35.0% faster)

    def test_function_call_in_multiline_comment(self):
        """Test that function calls in multi-line comments are NOT replaced."""
        source = "/* foo() should not be replaced */ bar()"
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 10.00μs -> 7.47μs (33.7% faster)


class TestEdgeCases:
    """Test cases for edge cases and unusual conditions."""

    def test_escaped_quote_in_string(self):
        """Test handling of escaped quotes inside strings."""
        source = r"'foo\'s bar' foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 7.99μs -> 7.41μs (7.81% faster)

    def test_escaped_backslash_in_string(self):
        """Test handling of escaped backslashes in strings."""
        source = r"'path\\to\\file' foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 8.41μs -> 7.76μs (8.36% faster)

    def test_method_call_not_replaced(self):
        """Test that method calls (preceded by dot) are NOT replaced."""
        source = "obj.foo() + foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 12.9μs -> 8.37μs (53.6% faster)

    def test_template_literal_simple(self):
        """Test handling of simple template literals."""
        source = "`foo()` bar()"
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 7.53μs -> 6.86μs (9.73% faster)

    def test_template_literal_with_expression(self):
        """Test handling of template literals with embedded expressions."""
        source = "`Value: ${foo()}` bar()"
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 9.50μs -> 9.01μs (5.51% faster)

    def test_template_literal_with_nested_braces(self):
        """Test handling of template literals with nested braces in expressions."""
        source = "`${obj.map(x => ({value: x}))}` foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 10.5μs -> 10.2μs (2.83% faster)

    def test_codeflash_capture_already_wrapped(self):
        """Test that already wrapped codeflash.capture calls are not double-wrapped."""
        source = "codeflash.capture(foo())"
        pattern = r"foo\(\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 16.9μs -> 10.5μs (60.3% faster)

    def test_nested_quotes_in_string(self):
        """Test handling of different quote types inside strings."""
        source = """'string with "quotes"' foo()"""
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 8.46μs -> 8.08μs (4.66% faster)

    def test_multiline_comment_not_closed(self):
        """Test handling of multi-line comment that extends to end of source."""
        source = "foo() /* comment starts here"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 9.20μs -> 6.59μs (39.5% faster)

    def test_function_call_at_end_of_source(self):
        """Test function call replacement at the very end of source."""
        source = "foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "bar()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 4.28μs -> 4.24μs (0.730% faster)

    def test_adjacent_strings(self):
        """Test handling of adjacent string literals."""
        source = "'foo()' \"foo()\" foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 9.13μs -> 8.05μs (13.4% faster)

    def test_comment_after_function_call(self):
        """Test function call followed by a comment."""
        source = "foo() // this is foo\nbar()"
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 10.5μs -> 8.23μs (27.1% faster)

    def test_escaped_character_in_comment(self):
        """Test comment handling with special characters."""
        source = "foo() // comment with \\ backslash\nbar()"
        pattern = r"foo\(\)|bar\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 11.4μs -> 8.42μs (35.6% faster)

    def test_regex_special_chars_in_string(self):
        """Test strings containing regex special characters."""
        source = r"'[a-z].*+?' foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 7.29μs -> 6.70μs (8.80% faster)

    def test_single_char_string(self):
        """Test handling of single character strings."""
        source = "'' 'a' foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 7.62μs -> 6.79μs (12.2% faster)

    def test_consecutive_escaped_quotes(self):
        """Test multiple consecutive escaped quotes."""
        source = r"'\"\"' foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 6.92μs -> 6.09μs (13.5% faster)

    def test_template_literal_escaped_backtick(self):
        """Test template literal with escaped backtick."""
        source = r"`escaped \` backtick` foo()"
        pattern = r"foo\(\)"
        replace_func = lambda m: "replaced()"
        codeflash_output = _safe_replace_function_calls(
            source, "foo", replace_func, pattern
        )
        result = codeflash_output  # 9.10μs -> 8.80μs (3.43% faster)

```

</details>


To edit these changes `git checkout
codeflash/optimize-pr2247-2026-01-25T08.38.25` and push.


[![Codeflash](https://img.shields.io/badge/Optimized%20with-Codeflash-yellow?style=flat&color=%23ffc428&logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDgwIiBoZWlnaHQ9ImF1dG8iIHZpZXdCb3g9IjAgMCA0ODAgMjgwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTI4Ni43IDAuMzc4NDE4SDIwMS43NTFMNTAuOTAxIDE0OC45MTFIMTM1Ljg1MUwwLjk2MDkzOCAyODEuOTk5SDk1LjQzNTJMMjgyLjMyNCA4OS45NjE2SDE5Ni4zNDVMMjg2LjcgMC4zNzg0MThaIiBmaWxsPSIjRkZDMDQzIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMzExLjYwNyAwLjM3ODkwNkwyNTguNTc4IDU0Ljk1MjZIMzc5LjU2N0w0MzIuMzM5IDAuMzc4OTA2SDMxMS42MDdaIiBmaWxsPSIjMEIwQTBBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMzA5LjU0NyA4OS45NjAxTDI1Ni41MTggMTQ0LjI3NkgzNzcuNTA2TDQzMC4wMjEgODkuNzAyNkgzMDkuNTQ3Vjg5Ljk2MDFaIiBmaWxsPSIjMEIwQTBBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMjQyLjg3MyAxNjQuNjZMMTg5Ljg0NCAyMTkuMjM0SDMxMC44MzNMMzYzLjM0NyAxNjQuNjZIMjQyLjg3M1oiIGZpbGw9IiMwQjBBMEEiLz4KPC9zdmc+Cg==)](https://codeflash.ai)
![Static
Badge](https://img.shields.io/badge/🎯_Optimization_Quality-high-green)

Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
Co-authored-by: Kevin Turcios <106575910+KRRT7@users.noreply.github.com>
2026-01-27 00:28:03 -05:00