ronantakizawa/codereview-bench huggingface dataset:
Repository: ManimCommunity/manim
File: manim/mobject/opengl/opengl_compatibility.py (Python)

Code before:
    depending on config.renderer. This metaclass should only need to be inherited
    on the lowest order inheritance classes such as Mobject and VMobject.
    """

    _converted_classes: list[type] = []

    def __new__(mcls, name: str, bases: tuple[type, ...], namespace: Any) -> type:
        if config.renderer == RendererType.OPENGL:
            # Must check class names to prevent
            # cyclic importing.
            base_names_to_opengl: dict[str, type] = {
                "Mobject": OpenGLMobject,
                "VMobject": OpenGLVMobject,
                "PMobject": OpenGLPMobject,
                "Mobject1D": OpenGLPMobject,
                "Mobject2D": OpenGLPMobject,
                "Surface": OpenGLSurface,
            }

            bases = tuple(
                base_names_to_opengl.get(base.__name__, base) for base in bases
            )

        return super().__new__(mcls, name, bases, namespace)

    def __init__(cls, name: str, bases: tuple[type, ...], namespace: Any):
        super().__init__(name, bases, namespace)
        cls._converted_classes.append(cls)


Review comment (suggestion):
```suggestion
    def __init__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any]):
```

Code after:
    depending on config.renderer. This metaclass should only need to be inherited
    on the lowest order inheritance classes such as Mobject and VMobject.
    """

    _converted_classes: list[type] = []

    def __new__(
        mcls, name: str, bases: tuple[type, ...], namespace: dict[str, Any]
    ) -> type:
        if config.renderer == RendererType.OPENGL:
            # Must check class names to prevent
            # cyclic importing.
            base_names_to_opengl: dict[str, type] = {
                "Mobject": OpenGLMobject,
                "VMobject": OpenGLVMobject,
                "PMobject": OpenGLPMobject,
                "Mobject1D": OpenGLPMobject,
                "Mobject2D": OpenGLPMobject,
                "Surface": OpenGLSurface,
            }

            bases = tuple(
                base_names_to_opengl.get(base.__name__, base) for base in bases
            )

        return super().__new__(mcls, name, bases, namespace)

    def __init__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any]):
        super().__init__(name, bases, namespace)
        cls._converted_classes.append(cls)
Repository: ManimCommunity/manim
File: manim/mobject/mobject.py (Python)

Code before:
    @height.setter
    def height(self, value: float):
        self.scale_to_fit_height(value)

    @property
    def depth(self) -> float:
        """The depth of the mobject.

        Returns
        -------
        :class:`float`

        See also
        --------
        :meth:`length_over_dim`

        """
        # Get the length across the Z dimension
        return self.length_over_dim(2)

    @depth.setter
    def depth(self, value: float):
        self.scale_to_fit_depth(value)

    # Can't be staticmethod because of point_cloud_mobject.py
    def get_array_attrs(self) -> list[Literal["points", "rgbas"]]:
        return ["points"]

    def apply_over_attr_arrays(self, func: MultiMappingFunction) -> Self:
        for attr in self.get_array_attrs():
            setattr(self, attr, func(getattr(self, attr)))
        return self

    # Displaying

    def get_image(self, camera=None) -> PixelArray:
        if camera is None:
            from ..camera.camera import Camera

            camera = Camera()
        camera.capture_mobject(self)
        return camera.get_image()

    def show(self, camera=None) -> None:
        self.get_image(camera=camera).show()

    def save_image(self, name: str | None = None) -> None:
        """Saves an image of only this :class:`Mobject` at its position to a png
        file.
        """
        self.get_image().save(

Review comment (suggestion):
After thinking about it for a while, I don't think that typing `Mobject.get_array_attrs()` as returning `list[Literal["points", "rgbas"]]` because `PMobject.get_array_attrs()` returns `["points", "rgbas"]` is the most correct solution.

I would say that both methods should be typehinted to return simply `list[str]`:
```suggestion
    def get_array_attrs(self) -> list[str]:
```

Code after:
    @width.setter
    def width(self, value: float):
        self.scale_to_fit_width(value)

    @property
    def height(self) -> float:
        """The height of the mobject.

        Returns
        -------
        :class:`float`

        Examples
        --------
        .. manim:: HeightExample

            class HeightExample(Scene):
                def construct(self):
                    decimal = DecimalNumber().to_edge(UP)
                    rect = Rectangle(color=BLUE)
                    rect_copy = rect.copy().set_stroke(GRAY, opacity=0.5)

                    decimal.add_updater(lambda d: d.set_value(rect.height))

                    self.add(rect_copy, rect, decimal)
                    self.play(rect.animate.set(height=5))
                    self.wait()

        See also
        --------
        :meth:`length_over_dim`

        """
        # Get the length across the Y dimension
        return self.length_over_dim(1)

    @height.setter
    def height(self, value: float):
        self.scale_to_fit_height(value)

    @property
    def depth(self) -> float:
        """The depth of the mobject.

        Returns
        -------
        :class:`float`

        See also
        --------
        :meth:`length_over_dim`
Repository: MotiaDev/motia
File: packages/workbench/src/components/endpoints/endpoint-side-panel.tsx (TypeScript)

Code before:
import { Sidebar } from '@/components/sidebar/sidebar'
import { ApiEndpoint } from '@/types/endpoint'
import { X } from 'lucide-react'
import { FC } from 'react'
import { EndpointBadge } from './endpoint-badge'
import { EndpointCall } from './endpoint-call'
import { EndpointDescription } from './endpoint-description'

type Props = { endpoint: ApiEndpoint; onClose: () => void }

export const EndpointSidePanel: FC<Props> = ({ endpoint, onClose }) => {
  return (
    <Sidebar
      initialWidth={600}
      title={
        <div className="flex flex-row gap-2 items-center">
          <EndpointBadge variant={endpoint.method as never}>{endpoint.method.toUpperCase()}</EndpointBadge>
          <span className="text-md font-bold">{endpoint.path}</span>
        </div>
      }
      onClose={onClose}
      tabs={[
        {
          label: 'Description',
          content: <EndpointDescription endpoint={endpoint} />,
        },
        {
          label: 'Call',
          content: <EndpointCall endpoint={endpoint} />,
        },
      ]}
      actions={[
        {
          icon: <X className="cursor-pointer w-4 h-4" onClick={onClose} />,
          onClick: onClose,
        },
      ]}
    />
  )
}


Review comment (suggestion):
suggestion: Details (which includes description)

```suggestion
          label: 'Details',
```

Code after:
import { Sidebar } from '@/components/sidebar/sidebar'
import { ApiEndpoint } from '@/types/endpoint'
import { X } from 'lucide-react'
import { FC } from 'react'
import { EndpointBadge } from './endpoint-badge'
import { EndpointCall } from './endpoint-call'
import { EndpointDescription } from './endpoint-description'

type Props = { endpoint: ApiEndpoint; onClose: () => void }

export const EndpointSidePanel: FC<Props> = ({ endpoint, onClose }) => {
  return (
    <Sidebar
      initialWidth={600}
      subtitle={endpoint.description}
      title={
        <div className="flex flex-row gap-2 items-center">
          <EndpointBadge variant={endpoint.method as never}>{endpoint.method.toUpperCase()}</EndpointBadge>
          <span className="text-md font-bold">{endpoint.path}</span>
        </div>
      }
      onClose={onClose}
      tabs={[
        {
          label: 'Details',
          content: <EndpointDescription endpoint={endpoint} />,
          'data-testid': 'endpoint-details-tab',
        },
        {
          label: 'Call',
          content: <EndpointCall endpoint={endpoint} />,
          'data-testid': 'endpoint-call-tab',
        },
      ]}
      actions={[
        {
          icon: <X className="cursor-pointer w-4 h-4" onClick={onClose} />,
          onClick: onClose,
        },
      ]}
    />
  )
}
Repository: MotiaDev/motia
File: packages/docs/components/AIReady.tsx (TypeScript)

Code before:
import { BentoCard, CardText } from './BentoCard'
import bgBento5 from '@/public/images/landing/bgBento5.webp'
import bento5 from '@/public/images/landing/bento5.webp'
import Image from 'next/image'
import { ParticlesBento } from './Particles'

export default function AIReady() {
  return (
    <div className="w-full overflow-clip rounded-[12px] lg:h-[480px] lg:basis-1/3">
      <BentoCard bg={bgBento5} stroke="bento5-stroke">
        <div className="fade-bottom relative w-full shrink p-[10px] lg:max-h-[330px]">
          <Image src={bento5} alt="AI Ready" className="object-fit object-center" />
          <div className="pointer-events-none absolute bottom-0 h-full w-full">
            <ParticlesBento />
          </div>
        </div>
        <CardText
          title="AI-Ready Workflows"
          subtitle="Bring AI to your backend: write agentic workflows, leverage Python/Ts/Js AI libraries, and connect them directly with APIs and jobs."
          textBoxWidth="w-[280px]"
        />
      </BentoCard>
    </div>
  )
}


Review comment (suggestion):
```suggestion
          subtitle="Bring AI to your backend: write agentic workflows, leverage Python/Node AI libraries, and connect them directly with APIs and jobs."
```

Code after:
import { BentoCard, CardText } from './BentoCard'
import bgBento5 from '@/public/images/landing/bgBento5.webp'
import bento5 from '@/public/images/landing/bento5.webp'
import Image from 'next/image'
import { ParticlesBento } from './Particles'

export default function AIReady() {
  return (
    <div className="w-full overflow-clip rounded-[12px] lg:h-[480px] lg:basis-1/3">
      <BentoCard bg={bgBento5} stroke="bento5-stroke">
        <div className="fade-bottom relative w-full shrink p-[10px] lg:max-h-[330px]">
          <Image src={bento5} alt="AI Ready" className="object-fit object-center" />
          <div className="pointer-events-none absolute bottom-0 h-full w-full">
            <ParticlesBento />
          </div>
        </div>
        <CardText
          title="AI-Ready Workflows"
          subtitle="Bring AI to your backend: write agentic workflows, leverage Python/Node AI libraries, and connect them directly with APIs and jobs."
          textBoxWidth="w-[280px]"
        />
      </BentoCard>
    </div>
  )
}
Repository: MotiaDev/motia
File: packages/snap/src/create/interactive.ts (TypeScript)

Code before:
      name: 'projectName',
      message: '2. Project name (leave blank to use current folder):',
      validate: (input: string) => {
        if (input && input.trim().length > 0) {
          if (!/^[a-zA-Z0-9][a-zA-Z0-9-_]*$/.test(input.trim())) {
            return 'Project name must start with a letter or number and contain only letters, numbers, hyphens, and underscores'
          }
        }
        return true
      },
      filter: (input: string) => input.trim(),
    },
    {
      type: 'confirm',
      name: 'proceed',
      message: '3. Proceed? [Y/n]:',
      default: true,
    },
  ])

  if (!answers.proceed) {
    context.log('cancelled', (message) => message.tag('info').append('\n❌ Project creation cancelled.'))
    return
  }

  context.log('creating', (message) => message.tag('info').append('\n🔨 Creating your Motia project...\n'))

  await create({
    projectName: answers.projectName || '.',
    template: answers.template,
    cursorEnabled: true, // Default to true for cursor rules
    context,
  })
}


Review comment (suggestion):
let's remove the info tag here

```suggestion
  context.log('creating', (message) => message.append('\n🔨 Creating your Motia project...\n'))
```

Code after:
      name: 'projectName',
      message: '2. Project name (leave blank to use current folder):',
      validate: (input: string) => {
        if (input && input.trim().length > 0) {
          if (!/^[a-zA-Z0-9][a-zA-Z0-9-_]*$/.test(input.trim())) {
            return 'Project name must start with a letter or number and contain only letters, numbers, hyphens, and underscores'
          }
        }
        return true
      },
      filter: (input: string) => input.trim(),
    },
    {
      type: 'confirm',
      name: 'proceed',
      message: '3. Proceed? [Y/n]:',
      default: true,
    },
  ])

  if (!answers.proceed) {
    context.log('cancelled', (message) => message.tag('info').append('\n❌ Project creation cancelled.'))
    return
  }

  context.log('creating', (message) => message.append('\n🔨 Creating your Motia project...\n'))

  await create({
    projectName: answers.projectName || '.',
    template: answers.template,
    cursorEnabled: true, // Default to true for cursor rules
    context,
  })
}
Repository: MotiaDev/motia
File: packages/snap/src/cloud/build/builders/python/router_template.py (Python)

Code before:
from typing import Dict, Callable, Any, Literal
# {{imports}}

class RouterPath:
    def __init__(self, step_name: str, method: Literal['get', 'post', 'put', 'delete', 'patch', 'options', 'head'], handler: Callable, config: Dict[str, Any]):
        self.step_name = step_name
        self.method = method
        self.handler = handler
        self.config = config

router_paths: Dict[str, RouterPath] = {
    # {{router paths}}
}


Review comment (suggestion):
can you add this?

```
# Generated code should look like this:
and the example
```

Code after:
from typing import Dict, Callable, Any, Literal
# {{imports}}


class RouterPath:
    def __init__(self, step_name: str, method: Literal['get', 'post', 'put', 'delete', 'patch', 'options', 'head'], handler: Callable, config: Dict[str, Any]):
        self.step_name = step_name
        self.method = method
        self.handler = handler
        self.config = config

router_paths: Dict[str, RouterPath] = {
    # Example:
    # 'POST /api/parallel-merge/python': RouterPath('Parallel Merge Python', 'post', route0_handler, route0_config)
    
    # {{router paths}}
}
Repository: MotiaDev/motia
File: packages/snap/src/cloud/new-deployment/deploy.ts (TypeScript)

Code before:
      if (state) {
        listener.onDeployProgress(state)
      }
    }, 1000)

    await new Promise<void>((resolve) => {
      subscription.addChangeListener((item) => {
        if (item && ['failed', 'completed'].includes(item.status)) {
          clearInterval(interval)
          listener.onDeployProgress(item)

          if (item.status === 'completed') {
            listener.onDeployEnd({
              output: item.outputs,
            })
          }

          client.close()
          resolve()
        }
      })
    })
  } else {
    context.log('deploy-progress', (message) =>
      message.tag('progress').append('Deployment in progress... You will be notified when it is completed'),
    )
  }
}


Review comment (suggestion):
Let's change it to show:

```
Deployment was initiated, check the progress in ${url}
```

We need to return the URL from the backend. Let's change `cloudApi.startDeployment` to return the URL. In the backend, while we don't have a page to view a deployment, let's just return the link to motia cloud

Code after:
      if (state) {
        listener.onDeployProgress(state)
      }
    }, 1000)

    await new Promise<void>((resolve) => {
      subscription.addChangeListener((item) => {
        if (item && ['failed', 'completed'].includes(item.status)) {
          clearInterval(interval)
          listener.onDeployProgress(item)

          if (item.status === 'completed') {
            listener.onDeployEnd({
              output: item.outputs,
            })
          }

          client.close()
          resolve()
        }
      })
    })
  } else {
    context.log('deploy-progress', (message) =>
      message
        .tag('progress')
        .append(`Deployment in progress... You can view the deployment at ${response.deploymentUrl}`),
    )
    client.close()
  }
}
Repository: MotiaDev/motia
File: packages/core/src/step-handlers.ts (TypeScript)

Code before:
              }
            }

            return { missingFields, extraFields, typeMismatches }
          }

          // ✅ Runtime validation block
          if (step.config.input) {
            if (typeof data !== 'object' || data === null) {
              logger.error(`❌ Validation failed for event "${step.config.name}": data is not an object`)
              return
            }

            const { missingFields, extraFields, typeMismatches } = validateEventData(
              data as Record<string, any>,
              step.config.input,
            )

            if (missingFields.length || extraFields.length || typeMismatches.length) {
              motia.printer.printEventInputValidationError(
                { topic: event.topic },
                { missingFields, extraFields, typeMismatches },
              )

              logger.error(`❌ Validation failed for event "${step.config.name}"`)
              return // stop execution if invalid
            }
          }

          try {
            await callStepFile({ step, data, traceId, tracer, logger }, motia)

            // eslint-disable-next-line @typescript-eslint/no-explicit-any
          } catch (error: any) {
            const message = typeof error === 'string' ? error : error.message
            logger.error(message)
          }
        },
      })
    })
  }

  const removeHandler = (step: Step<EventConfig>) => {
    const { config, filePath } = step
    const { subscribes } = config

    subscribes.forEach((subscribe) => {
      motia.eventManager.unsubscribe({ filePath, event: subscribe })
    })
  }


Review comment (suggestion):
let's just print a warning, we shouldn't block the data to flow.

warning means: something will not work correctly, please do something before an actual error happens

it will be very helpful in cases of errors like accessing field from undefined and so, developers will quickly realize it was a configuration issue

Code after:
      handlers.push({ topic: subscribe, handler })
    })

    handlerMap.set(filePath, handlers)
  }

  const removeHandler = (step: Step<EventConfig>) => {
    const { filePath } = step
    const handlers = handlerMap.get(filePath)

    if (handlers) {
      handlers.forEach(({ topic, handler }) => {
        queueManager.unsubscribe(topic, handler)
        globalLogger.debug('[step handler] unsubscribed handler', {
          filePath,
          topic,
          step: step.config.name,
        })
      })
      handlerMap.delete(filePath)
    }
  }

  eventSteps.forEach(createHandler)

  return { removeHandler, createHandler }
}
Repository: MotiaDev/motia
File: packages/snap/src/dev-watchers.ts (TypeScript)

Code before:
}

export const createDevWatchers = (
  lockedData: LockedData,
  server: MotiaServer,
  eventHandler: MotiaEventManager,
  cronManager: CronManager,
) => {
  const baseDir = process.cwd()
  const stepDir = path.join(baseDir, 'steps')
  const srcDir = path.join(baseDir, 'src')
  const watchers: Watcher[] = []

  if (existsSync(stepDir)) {
    const stepWatcher = new Watcher(stepDir, lockedData)
    setupWatcherHandlers(stepWatcher, lockedData, server, eventHandler, cronManager)
    stepWatcher.init()
    watchers.push(stepWatcher)
  }

  if (existsSync(srcDir)) {
    const srcWatcher = new Watcher(srcDir, lockedData)
    setupWatcherHandlers(srcWatcher, lockedData, server, eventHandler, cronManager)
    srcWatcher.init()
    watchers.push(srcWatcher)
  }

  return {
    stop: async () => {
      await Promise.all(watchers.map((watcher) => watcher.stop()))
    },
  }
}


Review comment (suggestion):
optional: i think we could reuse some code with list iteration here

```suggestion
  const baseDir = process.cwd()
  const dirs = [path.join(baseDir, 'steps'), path.join(baseDir, 'src')]
  const watchers: Watcher[] = []

  dirs.forEach(dir => {
    if (existsSync(dir)) {
      const watcher = new Watcher(dir, lockedData)
      setupWatcherHandlers(watcher, lockedData, server, eventHandler, cronManager)
      watcher.init()
      watchers.push(watcher)
    }
  })
```

Code after:
}

export const createDevWatchers = (
  lockedData: LockedData,
  server: MotiaServer,
  eventHandler: MotiaEventManager,
  cronManager: CronManager,
) => {
  const baseDir = process.cwd()
  const dirs = [path.join(baseDir, 'steps'), path.join(baseDir, 'src')]
  const watchers: Watcher[] = []

  dirs.forEach((dir) => {
    if (existsSync(dir)) {
      const watcher = new Watcher(dir, lockedData)
      setupWatcherHandlers(watcher, lockedData, server, eventHandler, cronManager)
      watcher.init()
      watchers.push(watcher)
    }
  })

  return {
    stop: async () => {
      await Promise.all(watchers.map((watcher) => watcher.stop()))
    },
  }
}
Repository: MotiaDev/motia
File: packages/core/src/logger.ts (TypeScript)

Code before:
import { prettyPrint } from './pretty-print'

const getLogLevel = () => process.env.LOG_LEVEL ?? 'info'
const isDebugEnabled = () => getLogLevel() === 'debug'
const isInfoEnabled = () => ['info', 'debug'].includes(getLogLevel())
const isWarnEnabled = () => ['warn', 'info', 'debug', 'trace'].includes(getLogLevel())

export type LogListener = (level: string, msg: string, args?: unknown) => void

export class Logger {
  /**
   * Why do we need two level of listeners?
   *
   * Core listeners pass along to children loggers.
   *
   * However, base listeners do not pass along to children loggers.
   * Those are specific to each logger in the hierarchy.
   */
  private readonly listeners: LogListener[] = []

  constructor(
    readonly isVerbose: boolean = false,
    private readonly meta: Record<string, unknown> = {},
    private readonly coreListeners: LogListener[] = [],
  ) {}

  child(meta: Record<string, unknown>): Logger {
    return new Logger(this.isVerbose, { ...this.meta, ...meta }, this.coreListeners)
  }

  private _log(level: string, msg: string, args?: any) {

Review comment (bug):
let's use number to do it:
```
const LEVELS = {
  NOTSET:   0,
  DEBUG:    10,
  INFO:     20,
  WARNING:  30,
  ERROR:    40,
  CRITICAL: 50,
};

if (LEVELS[log] >= currentLevel)
```

Code after:
import { prettyPrint } from './pretty-print'

const LEVELS = {
  NOTSET: 0,
  DEBUG: 10,
  INFO: 20,
  WARNING: 30,
  ERROR: 40,
  CRITICAL: 50,
} as const

const levelMap: Record<string, number> = {
  debug: LEVELS.DEBUG,
  info: LEVELS.INFO,
  warn: LEVELS.WARNING,
  warning: LEVELS.WARNING,
  error: LEVELS.ERROR,
  critical: LEVELS.CRITICAL,
}

const getLogLevel = (): number => {
  const level = process.env.LOG_LEVEL ?? 'info'
  return levelMap[level] ?? LEVELS.INFO
}

const shouldLog = (messageLevel: number): boolean => {
  return messageLevel >= getLogLevel()
}

export type LogListener = (level: string, msg: string, args?: unknown) => void