ronantakizawa/codereview-bench huggingface dataset:
Repository: tokio-rs/tokio
File: tokio/src/sync/tests/loom_oneshot.rs (Rust)

Code before:
        });

        // main thread is the rx thread
        drop(rx);

        tx_thread_join_handle.join().unwrap();
    });
}

#[test]
fn drop_rx_after_poll() {
    // Test that rx_task is properly deallocated when the receiver is dropped
    // after being polled (which sets rx_task), while the sender is concurrently
    // trying to send.
    loom::model(|| {
        let (tx, mut rx) = oneshot::channel::<i32>();

        // Spawn a thread that will poll the receiver once (setting rx_task),
        // then drop it.
        let rx_thread = thread::spawn(move || {
            // Poll once to set rx_task, then drop
            let _ = block_on(poll_fn(|cx| {
                let _ = Pin::new(&mut rx).poll(cx);
                // Always return Ready to exit the poll, then rx will be dropped
                Ready(())
            }));
            // rx is dropped here
        });

        // Sender tries to send concurrently
        let _ = tx.send(1);

        rx_thread.join().unwrap();
    });
}


Review comment (performance):
I think we can move the `poll` outside the thread, and have the only operation in the thread be `drop(rx)`.

The parallel part of Loom tests is really really expensive, so we should perform as few operations as possible in the parallel part of the test.

Code after:
        });

        // main thread is the rx thread
        drop(rx);

        tx_thread_join_handle.join().unwrap();
    });
}

#[test]
fn drop_rx_after_poll() {
    // Test that rx_task is properly deallocated when the receiver is dropped
    // after being polled (which sets rx_task), while the sender is concurrently
    // trying to send.
    loom::model(|| {
        let (tx, mut rx) = oneshot::channel::<i32>();

        // Poll once to set rx_task before entering the parallel part of the
        // test.
        let _ = block_on(poll_fn(|cx| {
            let _ = Pin::new(&mut rx).poll(cx);
            Ready(())
        }));

        // Drop the receiver concurrently with the sender trying to send.
        let rx_thread = thread::spawn(move || {
            drop(rx);
        });

        let _ = tx.send(1);

        rx_thread.join().unwrap();
    });
}
Repository: topoteretes/cognee
File: cognee/api/v1/cloud/routers/get_checks_router.py (Python)

Code before:
from fastapi import APIRouter, Depends, Request

from cognee.modules.users.models import User
from cognee.modules.users.methods import get_authenticated_user
from cognee.modules.cloud.operations import check_api_key
from cognee.modules.cloud.exceptions import CloudApiKeyMissingError


def get_checks_router():
    router = APIRouter()

    @router.post("/connection")
    async def get_connection_check_endpoint(
        request: Request, user: User = Depends(get_authenticated_user)
    ):
        api_token = request.headers.get("X-Api-Key")

        if api_token is None:
            # Return a graceful response for local/self-hosted installations
            return {
                "status": "local_mode",
                "message": "Running in local mode. Cloud features are not available without API key.",
                "cloud_available": False,
                "local_mode": True,
            }

        return await check_api_key(api_token)

    return router


Review comment (suggestion):
@turazashvili Can we add this error message into the `CloudApiKeyMissingError`? Let's reuse that error so we stay consistent in the future. You can be sure that this error will be returned only in local mode.

Code after:
from fastapi import APIRouter, Depends, Request

from cognee.modules.users.models import User
from cognee.modules.users.methods import get_authenticated_user
from cognee.modules.cloud.operations import check_api_key
from cognee.modules.cloud.exceptions import CloudApiKeyMissingError


def get_checks_router():
    router = APIRouter()

    @router.post("/connection")
    async def get_connection_check_endpoint(
        request: Request, user: User = Depends(get_authenticated_user)
    ):
        api_token = request.headers.get("X-Api-Key")

        if api_token is None:
            raise CloudApiKeyMissingError()

        return await check_api_key(api_token)

    return router
Repository: topoteretes/cognee
File: cognee-mcp/src/__init__.py (Python)

Code before:
from .server import main as server_main
import warnings
import sys


def main():
    """Deprecated main entry point for the package."""
    import asyncio

    warnings.warn(
        "The 'cognee' command for cognee-mcp is deprecated and will be removed in a future version. "
        "Please use 'cognee-mcp' instead to avoid conflicts with the main cognee library.",
        DeprecationWarning,
        stacklevel=2,
    )

    print("⚠️  DEPRECATION WARNING: Use 'cognee-mcp' command instead of 'cognee'", file=sys.stderr)
    print("   This avoids conflicts with the main cognee library.", file=sys.stderr)
    print(file=sys.stderr)

    asyncio.run(server_main())


def main_mcp():
    """Clean main entry point for cognee-mcp command."""
    import asyncio

    asyncio.run(server_main())


Review comment (suggestion):
Would be good to avoid using print with MCP as the STDIO mode for MCP uses standard input output to communicate instead of the network and print statements have been known to cause issues with this communication in the past

logging uses stderr for messages so it doesn't cause this problem

Code after:
from .server import main as server_main
import warnings
import sys


def main():
    """Deprecated main entry point for the package."""
    import asyncio

    deprecation_notice = """
DEPRECATION NOTICE
The CLI entry-point used to start the Cognee MCP service has been renamed from
"cognee" to "cognee-mcp". Calling the old entry-point will stop working in a
future release.

WHAT YOU NEED TO DO:
Locate every place where you launch the MCP process and replace the final
argument cognee → cognee-mcp.

For the example mcpServers block from Cursor shown below the change is:
{
  "mcpServers": {
    "Cognee": {
      "command": "uv",
      "args": [
        "--directory",
        "/path/to/cognee-mcp",
        "run",
        "cognee"              // <-- CHANGE THIS to "cognee-mcp"
      ]
    }
  }
}

Continuing to use the old "cognee" entry-point will result in failures once it
is removed, so please update your configuration and any shell scripts as soon
as possible.
"""

    warnings.warn(
        "The 'cognee' command for cognee-mcp is deprecated and will be removed in a future version. "
        "Please use 'cognee-mcp' instead to avoid conflicts with the main cognee library.",
Repository: topoteretes/cognee
File: cognee/memify_pipelines/consolidate_entity_descriptions.py (Python)

Code before:

def build_entity(id, name, entity_type, description):
    return Entity(
        id=UUID(id),
        name=name,
        is_a=entity_type,
        description=description,
    )


# endregion


async def consolidate_entity_descriptions(nodes) -> List[DataPoint]:
    system_prompt = render_prompt(prompt_name, {})
    enriched_data = []
    graph_engine = await get_graph_engine()

    for node in nodes:
        props = node["properties"]

        text = build_node_neighborhood_prompt(node)

        result = await query_LLM(text, system_prompt)

        for neighbor in node["neighbors"]:
            if neighbor["type"] != "EntityType":
                continue

            entity_type_node = neighbor
            node_types = await get_entity_type(graph_engine, entity_type_node)

            if not node_types:
                continue

            entity_type = build_entity_type(node_types)

            entity = build_entity(props["id"], props["name"], entity_type, result.description)

            enriched_data.append(entity)

    return enriched_data


async def consolidate_entity_descriptions_pipeline():
    extraction_tasks = [Task(get_entities_with_neighborhood)]

    enrichment_tasks = [
        Task(consolidate_entity_descriptions),
        Task(add_data_points),
    ]

Review comment (suggestion):
Could we move the EntityType resolution into get_entity_neighborhood so that each node's dict already comes with its resolved EntityType, instead of re-querying the graph later in consolidate_entity_descriptions? This way we could probably avoid the inner loop altogether. 

Code after:
        name=name,
        is_a=entity_type,
        description=description,
    )


async def generate_consolidated_entity(node, system_prompt) -> Entity:
    props = node["properties"]
    text = build_node_neighborhood_prompt(node)
    result = await query_LLM(text, system_prompt)
    entity_type = build_entity_type(node["entity_type"])
    entity = build_entity(props["id"], props["name"], entity_type, result.description)
    return entity


# endregion


async def generate_consolidated_entities(nodes) -> List[DataPoint]:
    system_prompt = render_prompt(prompt_name, {})

    consolidate_entity_descriptions_tasks = (
        generate_consolidated_entity(node, system_prompt) for node in nodes
    )

    return await asyncio.gather(*consolidate_entity_descriptions_tasks)


async def consolidate_entity_descriptions_pipeline():
    extraction_tasks = [Task(get_entities_with_neighborhood)]

    enrichment_tasks = [
        Task(generate_consolidated_entities),
        Task(add_data_points),
    ]

    await cognee.memify(
        extraction_tasks=extraction_tasks,
        enrichment_tasks=enrichment_tasks,
        data=[{}],  # A placeholder to prevent fetching the entire graph
    )
Repository: toss/es-toolkit
File: src/math/maxBy.ts (TypeScript)

Code before:
 *
 * @example
 * const people = [
 *  { name: 'Mark', age: 25 },
 *  { name: 'Nunu', age: 30 },
 *  { name: 'Overmars', age: 20 }
 *  ];
 *  const result = maxBy(people, person => person.age);
 *  // result will be { name: 'Nunu', age: 30 }
 */
export function maxBy<T>(elements: T[], selector: (element: T) => number): T | undefined {
  if (elements.length === 0) {
    return undefined;
  }
  let maxElement = elements[0];
  let max = selector(maxElement);

  for (const element of elements) {
    const value = selector(element);

    if (value > max) {
      max = value;
      maxElement = element;
    }
  }

  return maxElement;
}


Review comment (suggestion):
```suggestion
  let maxElement = elements[0];
  let max = -Infinity;

  for (const element of elements) {
    const value = selector(element);

    if (value > max) {
      max = value;
      maxElement = element;
    }
  }

  return maxElement;
```

Code after:
/**
 * Returns the element of the specified array that has the maximum value, according to the specified selector.
 *
 * This function takes an array of elements and a selector function, and returns the element with the maximum value according to the selector.
 *
 * @param {T[]} elements - An array of elements to be compared.
 * @param {(element: T) => number} selector - A function that takes an element and returns a number.
 * @returns {T} The element with the maximum value according to the selector.
 *
 * @example
 * const people = [
 *  { name: 'Mark', age: 25 },
 *  { name: 'Nunu', age: 30 },
 *  { name: 'Overmars', age: 20 }
 *  ];
 *  const result = maxBy(people, person => person.age);
 *  // result will be { name: 'Nunu', age: 30 }
 */
export function maxBy<T>(elements: T[], selector: (element: T) => number): T {
  let maxElement = elements[0];
  let max = -Infinity;

  for (const element of elements) {
    const value = selector(element);
    if (value > max) {
      max = value;
      maxElement = element;
    }
  }

  return maxElement;
}
Repository: toss/es-toolkit
File: src/math/maxBy.ts (TypeScript)

Code before:
/**
 * Returns the element of the specified array that has the maximum value, according to the specified selector.
 *
 * This function takes an array of elements and a selector function, and returns the element with the maximum value according to the selector.
 *
 * @param {T[]} elements - An array of elements to be compared.
 * @param {(element: T) => number} selector - A function that takes an element and returns a number.
 * @returns {T} The element with the maximum value according to the selector.
 *
 * @example
 * const people = [
 *  { name: 'Mark', age: 25 },
 *  { name: 'Nunu', age: 30 },
 *  { name: 'Overmars', age: 20 }
 *  ];
 *  const result = maxBy(people, person => person.age);
 *  // result will be { name: 'Nunu', age: 30 }
 */
export function maxBy<T>(elements: T[], selector: (element: T) => number): T {
  let maxElement = elements[0];
  let max = -Infinity;
  for (const element of elements) {
    const value = selector(element);
    if (value > max) {
      max = value;
      maxElement = element;
    }
  }

  return maxElement;
}


Review comment (suggestion):
```suggestion

  for (const element of elements) {
```

Code after:
/**
 * Returns the element of the specified array that has the maximum value, according to the specified selector.
 *
 * This function takes an array of elements and a selector function, and returns the element with the maximum value according to the selector.
 *
 * @param {T[]} elements - An array of elements to be compared.
 * @param {(element: T) => number} selector - A function that takes an element and returns a number.
 * @returns {T} The element with the maximum value according to the selector.
 *
 * @example
 * const people = [
 *  { name: 'Mark', age: 25 },
 *  { name: 'Nunu', age: 30 },
 *  { name: 'Overmars', age: 20 }
 *  ];
 *  const result = maxBy(people, person => person.age);
 *  // result will be { name: 'Nunu', age: 30 }
 */
export function maxBy<T>(elements: T[], selector: (element: T) => number): T {
  let maxElement = elements[0];
  let max = -Infinity;

  for (const element of elements) {
    const value = selector(element);
    if (value > max) {
      max = value;
      maxElement = element;
    }
  }

  return maxElement;
}
Repository: toss/es-toolkit
File: src/array/without.ts (TypeScript)

Code before:
/**
 * Creates an array excluding all given values using SameValueZero for equality comparisons.
 *
 * This function takes an input array and returns a new array that excludes all values
 * specified in the second argument. It uses SameValueZero for equality comparisons,
 * meaning that it considers -0 and +0 as equal but treats NaN as unequal to itself.
 *
 * @template T The type of elements in the array.
 * @param {ArrayLike<T>} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: ArrayLike<T>, ...values: T[]): T[] {
  if (!array || typeof array.length !== 'number') {
    return [];
  }
  const valuesSet = new Set(values);
  return Array.prototype.filter.call(array, item => !valuesSet.has(item));
}


Review comment (refactor):
```suggestion
 * Creates an array that excludes all specified values.
 *
 * It correctly excludes `NaN`, as it compares values using [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero).
```

Code after:
/**
 * Creates an array that excludes all specified values.
 *
 * It correctly excludes `NaN`, as it compares values using [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero).
 *
 * @template T The type of elements in the array.
 * @param {T[]} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: readonly T[], ...values: T[]): T[] {
  const valuesSet = new Set(values);
  return array.filter(item => !valuesSet.has(item));
}
Repository: toss/es-toolkit
File: src/array/without.ts (TypeScript)

Code before:
/**
 * Creates an array excluding all given values using SameValueZero for equality comparisons.
 *
 * This function takes an input array and returns a new array that excludes all values
 * specified in the second argument. It uses SameValueZero for equality comparisons,
 * meaning that it considers -0 and +0 as equal but treats NaN as unequal to itself.
 *
 * @template T The type of elements in the array.
 * @param {ArrayLike<T>} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: ArrayLike<T>, ...values: T[]): T[] {
  if (!array || typeof array.length !== 'number') {
    return [];
  }
  const valuesSet = new Set(values);
  return Array.prototype.filter.call(array, item => !valuesSet.has(item));
}


Review comment (suggestion):
```suggestion
 * @param {T[]} array - The array to filter.
```

Code after:
/**
 * Creates an array that excludes all specified values.
 *
 * It correctly excludes `NaN`, as it compares values using [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero).
 *
 * @template T The type of elements in the array.
 * @param {T[]} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: readonly T[], ...values: T[]): T[] {
  const valuesSet = new Set(values);
  return array.filter(item => !valuesSet.has(item));
}
Repository: toss/es-toolkit
File: src/array/without.ts (TypeScript)

Code before:
/**
 * Creates an array excluding all given values using SameValueZero for equality comparisons.
 *
 * This function takes an input array and returns a new array that excludes all values
 * specified in the second argument. It uses SameValueZero for equality comparisons,
 * meaning that it considers -0 and +0 as equal but treats NaN as unequal to itself.
 *
 * @template T The type of elements in the array.
 * @param {ArrayLike<T>} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: ArrayLike<T>, ...values: T[]): T[] {
  if (!array || typeof array.length !== 'number') {
    return [];
  }
  const valuesSet = new Set(values);
  return Array.prototype.filter.call(array, item => !valuesSet.has(item));
}


Review comment (suggestion):
```suggestion
export function without<T>(array: readonly T[], ...values: T[]): T[] {
```

Code after:
/**
 * Creates an array that excludes all specified values.
 *
 * It correctly excludes `NaN`, as it compares values using [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero).
 *
 * @template T The type of elements in the array.
 * @param {T[]} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: readonly T[], ...values: T[]): T[] {
  const valuesSet = new Set(values);
  return array.filter(item => !valuesSet.has(item));
}
Repository: toss/es-toolkit
File: src/array/without.ts (TypeScript)

Code before:
/**
 * Creates an array that excludes all specified values.
 *
 * It correctly excludes `NaN`, as it compares values using [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero).
 *
 * @template T The type of elements in the array.
 * @param {T[]} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: readonly T[], ...values: T[]): T[] {
  const valuesSet = new Set(values);
  return Array.prototype.filter.call(array, item => !valuesSet.has(item));
}


Review comment (suggestion):
```suggestion
  return array.filter(item => !valuesSet.has(item));
```

Code after:
/**
 * Creates an array that excludes all specified values.
 *
 * It correctly excludes `NaN`, as it compares values using [SameValueZero](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-samevaluezero).
 *
 * @template T The type of elements in the array.
 * @param {T[]} array - The array to filter.
 * @param {...T[]} values - The values to exclude.
 * @returns {T[]} A new array without the specified values.
 *
 * @example
 * // Removes the specified values from the array
 * without([1, 2, 3, 4, 5], 2, 4);
 * // Returns: [1, 3, 5]
 *
 * @example
 * // Removes specified string values from the array
 * without(['a', 'b', 'c', 'a'], 'a');
 * // Returns: ['b', 'c']
 */
export function without<T>(array: readonly T[], ...values: T[]): T[] {
  const valuesSet = new Set(values);
  return array.filter(item => !valuesSet.has(item));
}
Repository: toss/es-toolkit
File: src/function/index.ts (TypeScript)

Code before:
export { before } from './before.ts';
export { after } from './after.ts';
export { debounce } from './debounce.ts';
export { noop } from './noop.ts';
export { once } from './once.ts';
export { throttle } from './throttle.ts';
export { negate } from './negate.ts';
export { memoize, type MemoizeCache } from './memoize.ts';
export { ary } from './ary.ts';
export { unary } from './unary.ts';
export { partial } from './partial.ts';
export { partialRight } from './partialRight.ts';
export { rest } from './rest.ts';
export { curry } from './curry';
export { spread } from './spread.ts';


Review comment (suggestion):
```suggestion
export { curry } from './curry.ts';
```

Code after:
export { before } from './before.ts';
export { after } from './after.ts';
export { debounce } from './debounce.ts';
export { noop } from './noop.ts';
export { once } from './once.ts';
export { throttle } from './throttle.ts';
export { negate } from './negate.ts';
export { memoize, type MemoizeCache } from './memoize.ts';
export { ary } from './ary.ts';
export { unary } from './unary.ts';
export { partial } from './partial.ts';
export { partialRight } from './partialRight.ts';
export { rest } from './rest.ts';
export { curry } from './curry.ts';
export { spread } from './spread.ts';