schemas.py
Overview
The schemas.py file defines data models used for handling code execution requests and results within the InfiniFlow system. It leverages the pydantic library to create strongly-typed, validated schemas that ensure the integrity and correctness of data exchanged between components responsible for executing code snippets in various programming languages.
This file primarily contains two classes:
CodeExecutionRequest: Represents a request to execute a piece of code.CodeExecutionResult: Represents the outcome of executing that code, including status, output, errors, and resource usage.
These schemas facilitate structured communication between front-end clients, execution engines, and other backend services by defining clear contracts for the input and output data formats.
Classes
1. CodeExecutionResult
Description
CodeExecutionResult models the outcome of running a code snippet. It captures the execution status, outputs (standard output and error), exit code, resource usage metrics, and detailed error classifications if any occurred.
Attributes
Attribute | Type | Description |
|---|---|---|
|
| Enum indicating the overall result status (e.g., success, failure). |
|
| Captured standard output from the execution. |
|
| Captured standard error output from the execution. |
|
| Process exit code returned by the execution environment. |
|
| Optional detailed message or additional info about the result. |
|
| Time taken for execution in milliseconds. |
|
| Peak memory usage during execution in kilobytes. |
|
| Enum indicating if a resource limit was hit (CPU, memory, etc). |
|
| Enum specifying unauthorized access errors detected. |
|
| Enum classifying runtime errors encountered (exceptions, etc). |
Usage Example
from models.enums import ResultStatus
result = CodeExecutionResult(
status=ResultStatus.SUCCESS,
stdout="Hello, World!\n",
stderr="",
exit_code=0,
time_used_ms=150.5,
memory_used_kb=2048,
)
print(result.json())
2. CodeExecutionRequest
Description
CodeExecutionRequest defines the data structure for submitting code execution requests. It includes the code itself (base64 encoded), the programming language, and optional execution arguments.
Attributes
Attribute | Type | Description |
|---|---|---|
|
| Base64 encoded string containing the source code to execute. |
|
| Enum specifying the programming language of the code (default: Python). |
|
| Optional dictionary of arguments to be passed during execution. |
Validators
validate_base64(class method): Ensures that thecode_b64string is a valid Base64 encoded string. Raises aValueErrorif validation fails.
Usage Example
from models.enums import SupportLanguage
request = CodeExecutionRequest(
code_b64="cHJpbnQoIkhlbGxvLCBJbmZpbklGbG93ISIp", # base64 for: print("Hello, InfiniFlow!")
language=SupportLanguage.PYTHON,
arguments={"timeout": 5}
)
print(request.code_b64)
If an invalid base64 string is provided, the validator will raise an error:
try:
invalid_request = CodeExecutionRequest(code_b64="!!!not_base64!!!")
except ValueError as e:
print(e) # Output: Invalid base64 encoding: ...
Implementation Details and Algorithms
Data Validation: The
CodeExecutionRequestclass uses apydanticfield validator to verify that the providedcode_b64field contains a valid Base64 encoded string. This ensures that the backend will not attempt to decode malformed input, preventing runtime errors during code extraction.Use of Enums for Strong Typing: The file imports several enum types (
ResultStatus,ResourceLimitType, etc.) to classify various statuses and error types in a controlled manner. This design choice improves code clarity and reduces errors by limiting the range of acceptable values.Optional Fields for Flexibility: Both classes utilize optional fields to provide extensibility without mandating all data be present. For instance, resource usage statistics or detailed error types may be omitted if unavailable, allowing the same schema to be used across different execution environments or contexts.
Interaction with Other Components
models.enumsModule: This file imports enumerations from themodels.enumsmodule, indicating a shared definition of constants representing languages, statuses, error types, etc. This promotes consistency across the system.Execution Engine: The schemas are designed to be used by the code execution engine component, which accepts a
CodeExecutionRequestfor processing and returns aCodeExecutionResultafter execution.API Layer / Frontend: These schemas likely interface with API endpoints that accept user-submitted code and return execution results, enabling safe and validated data exchange.
Resource Monitoring and Security: The presence of fields related to resource limits and unauthorized access types suggests integration with system monitoring/security modules that track resource consumption and detect policy violations during code execution.
Mermaid Class Diagram
classDiagram
class CodeExecutionResult {
+status: ResultStatus
+stdout: str
+stderr: str
+exit_code: int
+detail: Optional[str]
+time_used_ms: Optional[float]
+memory_used_kb: Optional[float]
+resource_limit_type: Optional[ResourceLimitType]
+unauthorized_access_type: Optional[UnauthorizedAccessType]
+runtime_error_type: Optional[RuntimeErrorType]
}
class CodeExecutionRequest {
+code_b64: str
+language: SupportLanguage
+arguments: Optional[dict]
+validate_base64(v: str) str
}
CodeExecutionRequest ..> "models.enums.SupportLanguage"
CodeExecutionResult ..> "models.enums.ResultStatus"
CodeExecutionResult ..> "models.enums.ResourceLimitType"
CodeExecutionResult ..> "models.enums.UnauthorizedAccessType"
CodeExecutionResult ..> "models.enums.RuntimeErrorType"
Summary
The schemas.py file is a critical part of the InfiniFlow project’s code execution workflow. It provides validated, well-structured data models for submitting code to be executed and for reporting the results of that execution. By leveraging pydantic and enums, it ensures robustness, clarity, and consistency in handling code execution data, serving as a bridge between clients, execution services, and monitoring/security systems.