Skip to content

Commit b4ccd7d

Browse files
committed
fix: Standardize code formatting and improve readability across multiple files
- Added missing commas in field descriptions within `exec.py`, `files.py`, and `state_archival.py` to ensure proper syntax. - Reformatted multi-line expressions in `file.py`, `orchestrator.py`, and `runner.py` for better readability. - Updated test functions in `test_exec_languages.py`, `test_exec_workflow.py`, and `test_files.py` to follow consistent formatting practices. - Cleaned up unnecessary blank lines and improved alignment in various test files to enhance overall code clarity.
1 parent 60f0e3a commit b4ccd7d

16 files changed

Lines changed: 258 additions & 187 deletions

src/models/exec.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class RequestFile(BaseModel):
2525
name: str
2626
restore_state: bool = Field(
2727
default=False,
28-
description="If true, restore Python state from when this file was last used"
28+
description="If true, restore Python state from when this file was last used",
2929
)
3030

3131

src/models/files.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,15 @@ class FileInfo(BaseModel):
4242
path: str = Field(..., description="File path in the session")
4343
# State restoration fields (for Python state-file linking)
4444
execution_id: Optional[str] = Field(
45-
default=None,
46-
description="ID of the execution that created/last used this file"
45+
default=None, description="ID of the execution that created/last used this file"
4746
)
4847
state_hash: Optional[str] = Field(
4948
default=None,
50-
description="SHA256 hash of the Python state when this file was last used"
49+
description="SHA256 hash of the Python state when this file was last used",
5150
)
5251
last_used_at: Optional[datetime] = Field(
5352
default=None,
54-
description="Timestamp of when this file was last used in an execution"
53+
description="Timestamp of when this file was last used in an execution",
5554
)
5655

5756
class Config:

src/services/execution/runner.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -191,8 +191,11 @@ async def execute(
191191
else:
192192
# Standard execution (no state persistence)
193193
exit_code, stdout, stderr = await self._execute_code_in_container(
194-
container, request.code, request.language, request.timeout,
195-
args=request.args
194+
container,
195+
request.code,
196+
request.language,
197+
request.timeout,
198+
args=request.args,
196199
)
197200
end_time = datetime.utcnow()
198201

@@ -465,7 +468,9 @@ async def _execute_code_in_container(
465468
logger.debug(
466469
"Using REPL executor", container_id=container.id[:12], language=language
467470
)
468-
return await self._execute_via_repl(container, code, execution_timeout, args=args)
471+
return await self._execute_via_repl(
472+
container, code, execution_timeout, args=args
473+
)
469474

470475
# Standard execution path for non-REPL containers
471476
exec_command = lang_config.execution_command
@@ -539,8 +544,11 @@ def _is_repl_container(self, container: Container, language: str) -> bool:
539544
return False
540545

541546
async def _execute_via_repl(
542-
self, container: Container, code: str, timeout: int,
543-
args: Optional[List[str]] = None
547+
self,
548+
container: Container,
549+
code: str,
550+
timeout: int,
551+
args: Optional[List[str]] = None,
544552
) -> Tuple[int, str, str]:
545553
"""Execute code via REPL server in container.
546554

src/services/file.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,9 @@ async def store_uploaded_file(
591591
"size": len(content),
592592
"path": f"/{filename}",
593593
"type": "upload", # Mark as uploaded file
594-
"is_agent_file": "1" if is_agent_file else "0", # Read-only if agent file
594+
"is_agent_file": (
595+
"1" if is_agent_file else "0"
596+
), # Read-only if agent file
595597
}
596598

597599
await self._store_file_metadata(session_id, file_id, metadata)
@@ -744,9 +746,7 @@ async def cleanup_orphan_objects(self, batch_limit: int = 1000) -> int:
744746
logger.error("Orphan MinIO objects cleanup failed", error=str(e))
745747
return 0
746748

747-
async def get_file_state_hash(
748-
self, session_id: str, file_id: str
749-
) -> Optional[str]:
749+
async def get_file_state_hash(self, session_id: str, file_id: str) -> Optional[str]:
750750
"""Get the state hash associated with a file.
751751
752752
Args:

src/services/orchestrator.py

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,9 @@ async def _mount_explicit_files(
335335
mounted = []
336336
mounted_ids = set()
337337
file_refs = [] # Track for state-file linking
338-
restore_state_hash = None # Hash of state to restore (from first restore_state file)
338+
restore_state_hash = (
339+
None # Hash of state to restore (from first restore_state file)
340+
)
339341

340342
for file_ref in ctx.request.files:
341343
# Get file info
@@ -374,10 +376,12 @@ async def _mount_explicit_files(
374376
mounted_ids.add(key)
375377

376378
# Track file reference for state-file linking
377-
file_refs.append({
378-
"session_id": file_ref.session_id,
379-
"file_id": file_info.file_id,
380-
})
379+
file_refs.append(
380+
{
381+
"session_id": file_ref.session_id,
382+
"file_id": file_info.file_id,
383+
}
384+
)
381385

382386
# Check for restore_state flag (only for Python, use first file's state)
383387
if (
@@ -443,10 +447,12 @@ async def _auto_mount_session_files(
443447
mounted_ids.add(key)
444448

445449
# Track file reference for state-file linking
446-
file_refs.append({
447-
"session_id": ctx.session_id,
448-
"file_id": file_info.file_id,
449-
})
450+
file_refs.append(
451+
{
452+
"session_id": ctx.session_id,
453+
"file_id": file_info.file_id,
454+
}
455+
)
450456

451457
# Store file refs for later state_hash update
452458
ctx.mounted_file_refs = file_refs
@@ -461,9 +467,7 @@ async def _auto_mount_session_files(
461467

462468
return mounted
463469

464-
async def _load_state_by_hash(
465-
self, ctx: ExecutionContext, state_hash: str
466-
) -> None:
470+
async def _load_state_by_hash(self, ctx: ExecutionContext, state_hash: str) -> None:
467471
"""Load state by its hash for state-file restoration.
468472
469473
Tries Redis first, then MinIO cold storage.
@@ -472,9 +476,15 @@ async def _load_state_by_hash(
472476
# Try Redis first
473477
state = await self.state_service.get_state_by_hash(state_hash)
474478

475-
if not state and self.state_archival_service and settings.state_archive_enabled:
479+
if (
480+
not state
481+
and self.state_archival_service
482+
and settings.state_archive_enabled
483+
):
476484
# Try MinIO cold storage
477-
state = await self.state_archival_service.restore_state_by_hash(state_hash)
485+
state = await self.state_archival_service.restore_state_by_hash(
486+
state_hash
487+
)
478488

479489
if state:
480490
ctx.initial_state = state
@@ -820,11 +830,13 @@ async def _handle_generated_files(self, ctx: ExecutionContext) -> List[FileRef]:
820830
state_hash=ctx.new_state_hash, # Link file to current state
821831
)
822832

823-
generated.append(FileRef(
824-
id=file_id,
825-
name=filename,
826-
session_id=ctx.session_id, # Include for cross-message persistence
827-
))
833+
generated.append(
834+
FileRef(
835+
id=file_id,
836+
name=filename,
837+
session_id=ctx.session_id, # Include for cross-message persistence
838+
)
839+
)
828840
logger.info(
829841
"Generated file stored",
830842
session_id=ctx.session_id,

src/services/state_archival.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -415,9 +415,7 @@ def _get_state_by_hash_object_key(self, state_hash: str) -> str:
415415
"""Generate MinIO object key for a hash-indexed state."""
416416
return f"{self.STATE_BY_HASH_PREFIX}/{state_hash}/state.dat"
417417

418-
async def archive_state_by_hash(
419-
self, state_hash: str, state_data: str
420-
) -> bool:
418+
async def archive_state_by_hash(self, state_hash: str, state_data: str) -> bool:
421419
"""Archive a state indexed by its hash to MinIO.
422420
423421
Args:
@@ -498,7 +496,9 @@ async def restore_state_by_hash(self, state_hash: str) -> Optional[str]:
498496
response.release_conn()
499497
except S3Error as e:
500498
if e.code == "NoSuchKey":
501-
logger.debug("No archived state found by hash", hash=state_hash[:12])
499+
logger.debug(
500+
"No archived state found by hash", hash=state_hash[:12]
501+
)
502502
return None
503503
raise
504504

tests/functional/conftest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
"ts": ("console.log('ts: sum(1..10)=' + (1+2+3+4+5+6+7+8+9+10));", "55"),
3535
"go": (
3636
'package main\n\nimport (\n\t"fmt"\n)\n\nfunc main() {\n\ts := 0\n\t'
37-
'for i := 1; i <= 10; i++ {\n\t\ts += i\n\t}\n\t'
37+
"for i := 1; i <= 10; i++ {\n\t\ts += i\n\t}\n\t"
3838
'fmt.Printf("go: sum(1..10)=%d\\n", s)\n}',
3939
"55",
4040
),
@@ -44,7 +44,7 @@
4444
"55",
4545
),
4646
"c": (
47-
'#include <stdio.h>\nint main(){int s=0; for(int i=1;i<=10;i++) s+=i; '
47+
"#include <stdio.h>\nint main(){int s=0; for(int i=1;i<=10;i++) s+=i; "
4848
'printf("c: sum(1..10)=%d\\n", s); return 0;}',
4949
"55",
5050
),

tests/functional/test_exec_languages.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ async def test_language_execution(
2929
latency = time.perf_counter() - start
3030

3131
# Basic assertions
32-
assert response.status_code == 200, (
33-
f"Failed for {language_test_case['lang']}: {response.text}"
34-
)
32+
assert (
33+
response.status_code == 200
34+
), f"Failed for {language_test_case['lang']}: {response.text}"
3535

3636
data = response.json()
3737

@@ -61,7 +61,9 @@ class TestPythonExecution:
6161
"""Specific tests for Python execution features."""
6262

6363
@pytest.mark.asyncio
64-
async def test_python_with_imports(self, async_client, auth_headers, unique_entity_id):
64+
async def test_python_with_imports(
65+
self, async_client, auth_headers, unique_entity_id
66+
):
6567
"""Test Python execution with standard library imports."""
6668
response = await async_client.post(
6769
"/exec",
@@ -78,7 +80,9 @@ async def test_python_with_imports(self, async_client, auth_headers, unique_enti
7880
assert '{"ok": true}' in stdout or "{'ok': true}" in stdout.replace('"', "'")
7981

8082
@pytest.mark.asyncio
81-
async def test_python_with_numpy(self, async_client, auth_headers, unique_entity_id):
83+
async def test_python_with_numpy(
84+
self, async_client, auth_headers, unique_entity_id
85+
):
8286
"""Test Python execution with NumPy."""
8387
response = await async_client.post(
8488
"/exec",
@@ -94,7 +98,9 @@ async def test_python_with_numpy(self, async_client, auth_headers, unique_entity
9498
assert "mean=3.0" in response.json()["stdout"]
9599

96100
@pytest.mark.asyncio
97-
async def test_python_error_in_stderr(self, async_client, auth_headers, unique_entity_id):
101+
async def test_python_error_in_stderr(
102+
self, async_client, auth_headers, unique_entity_id
103+
):
98104
"""Test that Python errors appear in stderr, not as HTTP error."""
99105
response = await async_client.post(
100106
"/exec",

tests/functional/test_exec_workflow.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,11 @@ async def test_execution_creates_session(
1414
response = await async_client.post(
1515
"/exec",
1616
headers=auth_headers,
17-
json={"code": "print('hello')", "lang": "py", "entity_id": unique_entity_id},
17+
json={
18+
"code": "print('hello')",
19+
"lang": "py",
20+
"entity_id": unique_entity_id,
21+
},
1822
)
1923

2024
assert response.status_code == 200
@@ -170,7 +174,11 @@ async def test_exec_response_includes_state_fields(
170174
r = await async_client.post(
171175
"/exec",
172176
headers=auth_headers,
173-
json={"code": "data = [1,2,3]", "lang": "py", "entity_id": unique_entity_id},
177+
json={
178+
"code": "data = [1,2,3]",
179+
"lang": "py",
180+
"entity_id": unique_entity_id,
181+
},
174182
)
175183

176184
assert r.status_code == 200

tests/functional/test_files.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ class TestFileUpload:
77
"""Test POST /upload."""
88

99
@pytest.mark.asyncio
10-
async def test_upload_single_file(self, async_client, auth_headers, unique_entity_id):
10+
async def test_upload_single_file(
11+
self, async_client, auth_headers, unique_entity_id
12+
):
1113
"""Upload a single file using 'files' field."""
1214
files = {"files": ("test.txt", b"Hello World", "text/plain")}
1315
data = {"entity_id": unique_entity_id}

0 commit comments

Comments
 (0)