ronantakizawa/codereview-bench huggingface dataset:
Repository: meta-llama/llama-stack
File: src/llama_stack/apis/inspect/inspect.py (Python)

Code before:
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the terms described in the LICENSE file in
# the root directory of this source tree.

from typing import Protocol, runtime_checkable

from pydantic import BaseModel

from llama_stack.apis.version import LLAMA_STACK_API_V1
from llama_stack.providers.datatypes import HealthStatus
from llama_stack.schema_utils import json_schema_type, webmethod


@json_schema_type
class RouteInfo(BaseModel):
    """Information about an API route including its path, method, and implementing providers.

    :param route: The API endpoint path
    :param method: HTTP method for the route
    :param provider_types: List of provider types that implement this route
    """

    route: str
    method: str
    provider_types: list[str]


@json_schema_type
class HealthInfo(BaseModel):
    """Health status information for the service.

    :param status: Current health status of the service
    """

    status: HealthStatus


@json_schema_type
class VersionInfo(BaseModel):
    """Version information for the service.

    :param version: Version number of the service
    """

Review comment (suggestion):
nit. but we should probably use the `LLAMA_STACK_API_...` constants here to ensure that these dont diverge over time. 

Code after:
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the terms described in the LICENSE file in
# the root directory of this source tree.

from typing import Literal, Protocol, runtime_checkable

from pydantic import BaseModel

from llama_stack.apis.version import (
    LLAMA_STACK_API_V1,
)
from llama_stack.providers.datatypes import HealthStatus
from llama_stack.schema_utils import json_schema_type, webmethod

# Valid values for the route filter parameter.
# Actual API levels: v1, v1alpha, v1beta (filters by level, excludes deprecated)
# Special filter value: "deprecated" (shows deprecated routes regardless of level)
ApiFilter = Literal["v1", "v1alpha", "v1beta", "deprecated"]


@json_schema_type
class RouteInfo(BaseModel):
    """Information about an API route including its path, method, and implementing providers.

    :param route: The API endpoint path
    :param method: HTTP method for the route
    :param provider_types: List of provider types that implement this route
    """

    route: str
    method: str
    provider_types: list[str]


@json_schema_type
class HealthInfo(BaseModel):
    """Health status information for the service.

    :param status: Current health status of the service
    """

    status: HealthStatus
Repository: meta-llama/llama-stack
File: src/llama_stack/providers/remote/inference/vertexai/vertexai.py (Python)

Code before:
        try:
            # Get default credentials - will read from GOOGLE_APPLICATION_CREDENTIALS
            credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
            credentials.refresh(google.auth.transport.requests.Request())
            return str(credentials.token)
        except Exception:
            # If we can't get credentials, return empty string to let the env work with ADC directly
            return ""

    def get_base_url(self) -> str:
        """
        Get the Vertex AI OpenAI-compatible API base URL.

        Returns the Vertex AI OpenAI-compatible endpoint URL.
        Source: https://cloud.google.com/vertex-ai/generative-ai/docs/start/openai
        """
        return f"https://{self.config.location}-aiplatform.googleapis.com/v1/projects/{self.config.project}/locations/{self.config.location}/endpoints/openapi"

    async def list_provider_model_ids(self) -> Iterable[str]:
        """
        VertexAI doesn't currently offer a way to query a list of available models from Google's Model Garden
        For now we return a hardcoded version of the available models

        :return: An iterable of model IDs or None if not implemented
        """
        return ["vertex_ai/gemini-2.0-flash", "vertex_ai/gemini-2.5-flash", "vertex_ai/gemini-2.5-pro"]


Review comment (suggestion):
```suggestion
        return ["vertexai/gemini-2.0-flash", "vertexai/gemini-2.5-flash", "vertexai/gemini-2.5-pro"]
```

That seems more consistent with the provider's name.

Code after:
        try:
            # Get default credentials - will read from GOOGLE_APPLICATION_CREDENTIALS
            credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
            credentials.refresh(google.auth.transport.requests.Request())
            return str(credentials.token)
        except Exception:
            # If we can't get credentials, return empty string to let the env work with ADC directly
            return ""

    def get_base_url(self) -> str:
        """
        Get the Vertex AI OpenAI-compatible API base URL.

        Returns the Vertex AI OpenAI-compatible endpoint URL.
        Source: https://cloud.google.com/vertex-ai/generative-ai/docs/start/openai
        """
        return f"https://{self.config.location}-aiplatform.googleapis.com/v1/projects/{self.config.project}/locations/{self.config.location}/endpoints/openapi"

    async def list_provider_model_ids(self) -> Iterable[str]:
        """
        VertexAI doesn't currently offer a way to query a list of available models from Google's Model Garden
        For now we return a hardcoded version of the available models

        :return: An iterable of model IDs
        """
        return ["vertexai/gemini-2.0-flash", "vertexai/gemini-2.5-flash", "vertexai/gemini-2.5-pro"]
Repository: meta-llama/llama-stack
File: src/llama_stack/providers/remote/inference/vertexai/vertexai.py (Python)

Code before:
        from the default credentials and returns it for use with the OpenAI-compatible client.
        """
        try:
            # Get default credentials - will read from GOOGLE_APPLICATION_CREDENTIALS
            credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
            credentials.refresh(google.auth.transport.requests.Request())
            return str(credentials.token)
        except Exception:
            # If we can't get credentials, return empty string to let the env work with ADC directly
            return ""

    def get_base_url(self) -> str:
        """
        Get the Vertex AI OpenAI-compatible API base URL.

        Returns the Vertex AI OpenAI-compatible endpoint URL.
        Source: https://cloud.google.com/vertex-ai/generative-ai/docs/start/openai
        """
        return f"https://{self.config.location}-aiplatform.googleapis.com/v1/projects/{self.config.project}/locations/{self.config.location}/endpoints/openapi"

    async def list_provider_model_ids(self) -> Iterable[str]:
        """
        VertexAI doesn't currently offer a way to query a list of available models from Google's Model Garden
        For now we return a hardcoded version of the available models

        :return: An iterable of model IDs or None if not implemented
        """
        return ["vertexai/gemini-2.0-flash", "vertexai/gemini-2.5-flash", "vertexai/gemini-2.5-pro"]


Review comment (suggestion):
```suggestion
        :return: An iterable of model IDs
```

None is never returned, so it's slightly misleading

Code after:
        from the default credentials and returns it for use with the OpenAI-compatible client.
        """
        try:
            # Get default credentials - will read from GOOGLE_APPLICATION_CREDENTIALS
            credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
            credentials.refresh(google.auth.transport.requests.Request())
            return str(credentials.token)
        except Exception:
            # If we can't get credentials, return empty string to let the env work with ADC directly
            return ""

    def get_base_url(self) -> str:
        """
        Get the Vertex AI OpenAI-compatible API base URL.

        Returns the Vertex AI OpenAI-compatible endpoint URL.
        Source: https://cloud.google.com/vertex-ai/generative-ai/docs/start/openai
        """
        return f"https://{self.config.location}-aiplatform.googleapis.com/v1/projects/{self.config.project}/locations/{self.config.location}/endpoints/openapi"

    async def list_provider_model_ids(self) -> Iterable[str]:
        """
        VertexAI doesn't currently offer a way to query a list of available models from Google's Model Garden
        For now we return a hardcoded version of the available models

        :return: An iterable of model IDs
        """
        return ["vertexai/gemini-2.0-flash", "vertexai/gemini-2.5-flash", "vertexai/gemini-2.5-pro"]
Repository: meta-llama/llama-stack
File: src/llama_stack/core/server/server.py (Python)

Code before:

    if config.telemetry.enabled:
        app.add_middleware(TracingMiddleware, impls=impls, external_apis=external_apis)

    return app


def _log_run_config(run_config: StackRunConfig):
    """Logs the run config with redacted fields and disabled providers removed."""
    logger.info("Run configuration:")
    safe_config = redact_sensitive_fields(run_config.model_dump(mode="json"))
    clean_config = remove_disabled_providers(safe_config)
    logger.info(yaml.dump(clean_config, indent=2))


def extract_path_params(route: str) -> list[str]:
    segments = route.split("/")
    params = [seg[1:-1] for seg in segments if seg.startswith("{") and seg.endswith("}")]
    # to handle path params like {param:path}
    params = [param.split(":")[0] for param in params]
    return params


def remove_disabled_providers(obj):
    if isinstance(obj, dict):
        # Filter out items where provider_id is explicitly disabled or empty
        if "provider_id" in obj and obj["provider_id"] in ("__disabled__", ""):
            return None
        return {k: v for k, v in ((k, remove_disabled_providers(v)) for k, v in obj.items()) if v is not None}
    elif isinstance(obj, list):
        return [item for item in (remove_disabled_providers(i) for i in obj) if item is not None]
    else:
        return obj


Review comment (suggestion):
yes we had added this behavior when our starter run.yaml had models also listed and disabled via these methods. I _believe_ this is now not needed but if you could double check environment variables which end up enabling or disabling certain entries in run.yaml which would cause this block to trigger, that would be great.

Code after:

    if config.telemetry.enabled:
        app.add_middleware(TracingMiddleware, impls=impls, external_apis=external_apis)

    return app


def _log_run_config(run_config: StackRunConfig):
    """Logs the run config with redacted fields and disabled providers removed."""
    logger.info("Run configuration:")
    safe_config = redact_sensitive_fields(run_config.model_dump(mode="json"))
    clean_config = remove_disabled_providers(safe_config)
    logger.info(yaml.dump(clean_config, indent=2))


def extract_path_params(route: str) -> list[str]:
    segments = route.split("/")
    params = [seg[1:-1] for seg in segments if seg.startswith("{") and seg.endswith("}")]
    # to handle path params like {param:path}
    params = [param.split(":")[0] for param in params]
    return params


def remove_disabled_providers(obj):
    if isinstance(obj, dict):
        # Filter out items where provider_id is explicitly disabled or empty
        if "provider_id" in obj and obj["provider_id"] in ("__disabled__", "", None):
            return None
        return {k: v for k, v in ((k, remove_disabled_providers(v)) for k, v in obj.items()) if v is not None}
    elif isinstance(obj, list):
        return [item for item in (remove_disabled_providers(i) for i in obj) if item is not None]
    else:
        return obj
Repository: microsoft/CSS-Exchange
File: Diagnostics/HealthChecker/DataCollection/ExchangeInformation/Get-ExchangeServerCertificates.ps1 (PowerShell)

Code before:
﻿# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

. $PSScriptRoot\..\..\..\..\Shared\ErrorMonitorFunctions.ps1
function Get-ExchangeServerCertificates {
    param(
        [Parameter(Mandatory = $false)]
        [switch]
        $ExcludeCertificatesOnSkiplist
    )

    Write-Verbose "Calling: $($MyInvocation.MyCommand)"

    function NewCertificateExclusionEntry {
        param(
            [Parameter(Mandatory = $true)]
            [string]
            $IssuerOrSubjectPattern,
            [Parameter(Mandatory = $true)]
            [bool]
            $IsSelfSigned
        )

        [PSCustomObject]@{
            IorSPattern  = $IssuerOrSubjectPattern
            IsSelfSigned = $IsSelfSigned
        }
    }

    function ShouldCertificateBeSkipped {
        [OutputType("System.Boolean")]
        param (
            [Parameter(Mandatory = $true)]
            [PSCustomObject]

Review comment (suggestion):
Let's remove the parameter as it isn't needed. 

We also have `$Script:Server` within the script so moving to a share type location would require the removal of that anyways. 

Code after:
﻿# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

. $PSScriptRoot\..\..\..\..\Shared\ErrorMonitorFunctions.ps1
function Get-ExchangeServerCertificates {
    param()

    Write-Verbose "Calling: $($MyInvocation.MyCommand)"

    function NewCertificateExclusionEntry {
        [OutputType("System.Object")]
        param(
            [Parameter(Mandatory = $true)]
            [string]
            $IssuerOrSubjectPattern,
            [Parameter(Mandatory = $true)]
            [bool]
            $IsSelfSigned
        )

        return [PSCustomObject]@{
            IorSPattern  = $IssuerOrSubjectPattern
            IsSelfSigned = $IsSelfSigned
        }
    }

    function ShouldCertificateBeSkipped {
        [OutputType("System.Boolean")]
        param (
            [Parameter(Mandatory = $true)]
            [PSCustomObject]
            $Exclusions,
            [Parameter(Mandatory = $true)]
            [System.Security.Cryptography.X509Certificates.X509Certificate2]
Repository: microsoft/CSS-Exchange
File: Diagnostics/AVTester/Write-SimpleLogFile.ps1 (PowerShell)

Code before:

.EXAMPLE
Write-SimpleLogFile -String "Start ProcessA" -FileName MyLogFile.log -Path "C:\temp"

Writes "[Date] - Start ProcessA" to C:\temp\MyLogFile.log

.EXAMPLE
Write-SimpleLogFile -String "Start ProcessB" -FileName MyLogFile.log -OutHost -Path "C:\temp"

Writes "[Date] - Start ProcessB" to C:\temp\MyLogFile and to the Host

#>
function Write-SimpleLogFile {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [string]$String,

        [parameter(Mandatory)]
        [ValidateScript({
                if (Test-Path -Path $_ -PathType Container) { $true }
                else { throw "Path $_ is not valid" }
            })]
        [String]$Path,

        [Parameter(Mandatory = $true)]
        [string]$FileName,

        [switch]$OutHost,

        [switch]$OpenLog

    )

    begin {
        # Get our log file path
        $LogFile = Join-Path $Path $FileName

        if ($OpenLog) {
            Notepad.exe $LogFile
            exit
        }
    }
    process {

        # Get the current date
        [string]$date = Get-Date -Format G

        # Build output string
        [string]$logString = ( "[" + $date + "] - " + $string)

Review comment (suggestion):
This is going to break `Set-ExchAVExclusions.ps1` the way you have this setup. By creating a new mandatory parameter to `Write-SimpleLogFile` that is used in this other script, we need to also modify that script or update it so it accepts a default value. 

Code after:

.EXAMPLE
Write-SimpleLogFile -String "Start ProcessA" -FileName MyLogFile.log -Path "C:\temp"

Writes "[Date] - Start ProcessA" to C:\temp\MyLogFile.log

.EXAMPLE
Write-SimpleLogFile -String "Start ProcessB" -FileName MyLogFile.log -OutHost -Path "C:\temp"

Writes "[Date] - Start ProcessB" to C:\temp\MyLogFile and to the Host

#>
function Write-SimpleLogFile {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [string]$String,

        [parameter(Mandatory)]
        [ValidateScript({
                $filePath = Split-Path -Path $_ -Parent
                if ($filePath -eq "") { $filePath = "." }
                if ((Test-Path -Path $filePath -PathType Container) -and ((Test-Path -Path $_ -PathType Leaf) -or -not ((Test-Path -Path $_ -PathType Container)))) { $true }
                else { throw "Path $_ is not valid" }
            })]
        [string]$LogFile,

        [switch]$OutHost,

        [switch]$OpenLog

    )

    begin {
        if ($OpenLog) {
            Notepad.exe $LogFile
            exit
        }
    }
    process {

        # Get the current date
        [string]$date = Get-Date -Format G

        # Build output string
        [string]$logString = ( "[" + $date + "] - " + $string)

        # Write everything to our log file and the screen
        $logString | Out-File -FilePath $LogFile -Append -Confirm:$false
        if ($OutHost) { Write-Host $logString }
Repository: microsoft/CSS-Exchange
File: Databases/VSSTester/DiskShadow/Invoke-CreateDiskShadowFile.ps1 (PowerShell)

Code before:
        }
    }

    # Here is where we start adding the appropriate volumes or MountPoints to the DiskShadow config file
    # We make sure that we add only one Logical volume when we detect the EDB and log files
    # are on the same volume

    for ($i = 0; $i -lt $deviceIDs.Count; $i++) {
        $id = $deviceIDs[$i]
        Write-Debug -Message ('$id = ' + $id.ToString())
        $addVol = "add volume $id alias vss_test_$i"
        Write-Host $addVol
        Out-DHSFile $addVol
    }

    Out-DHSFile "create"
    Out-DHSFile " "
    Write-Host "$(Get-Date) Getting drive letters for exposing backup snapshot"

    # expose the drives
    for ($i = 0; $i -lt $deviceIDs.Count; $i++) {
        $dbVolStr = "expose %vss_test_$($i)% $($DriveLetters[$i]):"
        Out-DHSFile $dbVolStr
    }

    # ending data of file
    Out-DHSFile "end backup"

    # return the drive letters we used
    return $DriveLetters | Select-Object -First ($deviceIDs.Count)
}


Review comment (suggestion):
There doesn't appear to be logic to handle if `$DriverLetters` doesn't contain more than 1 letter for when we are trying to backup a database that doesn't have the log files on the same drive path. 

Code after:
    }

    # Here is where we start adding the appropriate volumes or MountPoints to the DiskShadow config file
    # We make sure that we add only one Logical volume when we detect the EDB and log files
    # are on the same volume

    for ($i = 0; $i -lt $deviceIDs.Count; $i++) {
        $id = $deviceIDs[$i]
        Write-Debug -Message ('$id = ' + $id.ToString())
        $addVol = "add volume $id alias vss_test_$i"
        Write-Host $addVol
        Out-DHSFile $addVol
    }

    Out-DHSFile "create"
    Out-DHSFile " "
    Write-Host "$(Get-Date) Getting drive letters for exposing backup snapshot"

    # expose the drives
    if ($deviceIDs.Count -lt $DriveLetters.Count) {
        Write-Warning "Determined that we need $($deviceIDs.Count) drive letters to expose the snapshots, but only $($DriveLetters.Count) were provided. Exiting."
        exit
    }

    for ($i = 0; $i -lt $deviceIDs.Count; $i++) {
        $dbVolStr = "expose %vss_test_$($i)% $($DriveLetters[$i]):"
        Out-DHSFile $dbVolStr
    }

    # ending data of file
    Out-DHSFile "end backup"

    # return the drive letters we used
    return $DriveLetters | Select-Object -First ($deviceIDs.Count)
}
Repository: microsoft/CSS-Exchange
File: Calendar/CalLogHelpers/CalLogCSVFunctions.ps1 (PowerShell)

Code before:
    )
    if ([string]::IsNullOrEmpty($DateTime) -or
        $DateTime -eq "N/A" -or
        $DateTime -eq "NotFound") {
        return ""
    }
    return [DateTime]$DateTime
}

function GetAttendeeCount {
    param(
        [string] $AttendeeCollection
    )
    if ($From.SmtpAddress -ne "NotFound") {
        return ($AttendeeCollection -split ';').Count
    } else {
        return "-"
    }
}

function CompressedVersion {
    [string] $CompressedString = ""
    if ($CalLog.AppointmentSequenceNumber -eq "NotFound" -or [string]::IsNullOrEmpty($CalLog.AppointmentSequenceNumber)) {
        $CompressedString = "-:"
    } else {
        $CompressedString = $CalLog.AppointmentSequenceNumber.ToString() + ":"
    }
    if ($CalLog.AppointmentLastSequenceNumber -eq "NotFound" -or [string]::IsNullOrEmpty($CalLog.AppointmentLastSequenceNumber)) {
        $CompressedString += "-:"
    } else {
        $CompressedString += $CalLog.AppointmentLastSequenceNumber.ToString() + ":"
    }
    if ($CalLog.ItemVersion -eq "NotFound" -or [string]::IsNullOrEmpty($CalLog.ItemVersion)) {
        $CompressedString += "-"
    } else {
        $CompressedString += $CalLog.ItemVersion.ToString()
    }

    return $CompressedString
}


Review comment (suggestion):
`$CalLog` is a local variable the function `BuildCSV` and `CompressedVersion` is not within that function. Therefore, we should pass the variable or move the function inside the `BuildCSV` #Resolved

Code after:
    )
    if ([string]::IsNullOrEmpty($DateTime) -or
        $DateTime -eq "N/A" -or
        $DateTime -eq "NotFound") {
        return ""
    }
    return [DateTime]$DateTime
}

function GetAttendeeCount {
    param(
        [string] $AttendeeCollection
    )
    if ($From.SmtpAddress -ne "NotFound") {
        return ($AttendeeCollection -split ';').Count
    } else {
        return "-"
    }
}

function CompressVersionInfo {
    param(
        $CalLog
    )
    [string] $CompressedString = ""
    if ($CalLog.AppointmentSequenceNumber -eq "NotFound" -or [string]::IsNullOrEmpty($CalLog.AppointmentSequenceNumber)) {
        $CompressedString = "-:"
    } else {
        $CompressedString = $CalLog.AppointmentSequenceNumber.ToString() + ":"
    }
    if ($CalLog.AppointmentLastSequenceNumber -eq "NotFound" -or [string]::IsNullOrEmpty($CalLog.AppointmentLastSequenceNumber)) {
        $CompressedString += "-:"
    } else {
        $CompressedString += $CalLog.AppointmentLastSequenceNumber.ToString() + ":"
    }
    if ($CalLog.ItemVersion -eq "NotFound" -or [string]::IsNullOrEmpty($CalLog.ItemVersion)) {
        $CompressedString += "-"
    } else {
        $CompressedString += $CalLog.ItemVersion.ToString()
    }

    return $CompressedString
}