refactor: remove redundant comments and docstrings (#6527)
* refactor: remove redundant comments and docstrings * fix(signal): annotate async context manager as a generator
This commit is contained in:
1 parent
cb3ba45317
commit
a4d2430140
922 files changed
+406
-7738
No files matched your search
@@ -1,5 +1,3 @@
|
||||
"""Job-store edits must not cancel the timer task executing an agent turn."""
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
@@ -76,7 +74,6 @@ async def test_edit_during_timer_execution_preserves_turn(
|
||||
if not edit_from_callback:
|
||||
edit_store()
|
||||
release.set()
|
||||
# Rearming cancels the finished tick; the job outcome must still be successful.
|
||||
await asyncio.wait((timer,))
|
||||
if not timer.cancelled():
|
||||
timer.result()
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Editing task instructions must not postpone or drop an existing occurrence."""
|
||||
|
||||
import asyncio
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
@@ -49,7 +47,6 @@ async def test_metadata_edit_preserves_due_occurrence(tmp_path, monkeypatch, kin
|
||||
async def execute(job):
|
||||
calls.append((job.id, job.name, job.payload.message))
|
||||
|
||||
# A separate service consumes the persisted edit, as the gateway does.
|
||||
reader = CronService(store_path, on_job=execute)
|
||||
loaded = reader.get_job(job.id)
|
||||
assert loaded is not None
|
||||
|
||||
@@ -32,8 +32,6 @@ def _seeded_store(tmp_path: Path) -> tuple[CronService, Path]:
|
||||
schedule=CronSchedule(kind="cron", expr="0 10 * * *", tz="Asia/Kuwait"),
|
||||
message="hello",
|
||||
)
|
||||
# add_job appended to action.jsonl; flush to jobs.json by toggling
|
||||
# ``_running`` long enough for ``_merge_action`` to do its rewrite.
|
||||
service._running = True
|
||||
try:
|
||||
service._load_store()
|
||||
@@ -71,8 +69,6 @@ def test_save_store_is_atomic(tmp_path: Path) -> None:
|
||||
cannot leave the destination truncated or invalid."""
|
||||
service, store_path = _seeded_store(tmp_path)
|
||||
|
||||
# Simulate an arbitrary save and confirm the result parses cleanly and
|
||||
# no orphan ``.tmp`` is left behind.
|
||||
service._save_store()
|
||||
data = json.loads(store_path.read_text(encoding="utf-8"))
|
||||
assert len(data["jobs"]) == 1
|
||||
@@ -91,8 +87,6 @@ def test_save_store_failure_does_not_corrupt_existing_file(
|
||||
service, store_path = _seeded_store(tmp_path)
|
||||
original = store_path.read_bytes()
|
||||
|
||||
# Inject a failure inside the temp-file write. ``os.replace`` should
|
||||
# never run; the destination must keep its previous content.
|
||||
real_open = open
|
||||
|
||||
def boom(path, *args, **kwargs): # type: ignore[no-untyped-def]
|
||||
@@ -145,7 +139,6 @@ def test_action_log_survives_failed_store_save(
|
||||
assert store_path.read_bytes() == original_store
|
||||
assert action_path.read_bytes() == pending_actions
|
||||
|
||||
# Recover from disk, without relying on the failed gateway's dirty snapshot.
|
||||
restarted = CronService(store_path)
|
||||
restarted._running = True
|
||||
assert [(j.id, j.name) for j in restarted.list_jobs(include_disabled=True)] == expected
|
||||
@@ -196,7 +189,6 @@ def test_saved_actions_can_be_replayed_if_log_cleanup_fails(
|
||||
def test_atomic_write_ignores_unsupported_directory_fsync(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""vboxsf-like filesystems can open directories but reject directory fsync."""
|
||||
store_path = tmp_path / "cron" / "jobs.json"
|
||||
dir_fd = 987654
|
||||
|
||||
@@ -236,7 +228,6 @@ def test_load_jobs_preserves_corrupt_store_and_returns_none(
|
||||
service = CronService(store_path)
|
||||
assert service._load_jobs() is None
|
||||
|
||||
# Original path is gone; a ``.corrupt-<ts>`` backup exists alongside it.
|
||||
assert not store_path.exists()
|
||||
backups = list(store_path.parent.glob("jobs.json.corrupt-*"))
|
||||
assert len(backups) == 1
|
||||
@@ -258,10 +249,8 @@ def test_start_refuses_to_overwrite_corrupt_store(tmp_path: Path) -> None:
|
||||
with pytest.raises(RuntimeError, match="corrupt"):
|
||||
asyncio.run(service.start())
|
||||
|
||||
# Service is left in a stopped state so the operator notices.
|
||||
assert service._running is False
|
||||
|
||||
# And the corrupt file is still recoverable from the .corrupt-<ts> copy.
|
||||
backups = list(store_path.parent.glob("jobs.json.corrupt-*"))
|
||||
assert len(backups) == 1
|
||||
|
||||
@@ -273,15 +262,12 @@ def test_load_store_falls_back_to_in_memory_on_corruption_after_start(
|
||||
rclone-mounted Drive returns a partial read), the service must keep
|
||||
using its existing in-memory snapshot instead of dropping every job."""
|
||||
service, store_path = _seeded_store(tmp_path)
|
||||
# Force load so ``self._store`` is populated.
|
||||
service._load_store()
|
||||
snapshot = service._store
|
||||
assert snapshot is not None and len(snapshot.jobs) == 1
|
||||
|
||||
# Now corrupt the file on disk.
|
||||
store_path.write_text("\x00garbage\x00", encoding="utf-8")
|
||||
|
||||
# Subsequent reload returns the in-memory snapshot, not None or empty.
|
||||
result = service._load_store()
|
||||
assert result is snapshot
|
||||
assert len(result.jobs) == 1
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Scheduled replies and explicit sends share the normal agent delivery path."""
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
@@ -50,7 +48,6 @@ async def test_moved_cron_keeps_reply_send_and_prompt_prefix_contract(tmp_path,
|
||||
ctx = current_request_context()
|
||||
assert ctx is not None
|
||||
trigger = ctx.metadata.get(CRON_TRIGGER_META)
|
||||
# Serialize at the provider boundary, before the runner appends tool results.
|
||||
requests.append(json.loads(json.dumps({
|
||||
"tools": kwargs["tools"], "messages": kwargs["messages"],
|
||||
"run": trigger["run_id"] if trigger else None,
|
||||
@@ -98,7 +95,6 @@ async def test_moved_cron_keeps_reply_send_and_prompt_prefix_contract(tmp_path,
|
||||
if message.event is None and message.content:
|
||||
outbound.append(message)
|
||||
normal = [m for m in outbound if (m.channel, m.chat_id) == ("telegram", "new")]
|
||||
# Normal backend replies and legacy same-chat sends each arrive once.
|
||||
assert [m.content for m in normal] == ["Drink water"]
|
||||
assert normal[0].metadata["message_thread_id"] == 42
|
||||
extra = [m for m in outbound if m not in normal]
|
||||
@@ -108,8 +104,6 @@ async def test_moved_cron_keeps_reply_send_and_prompt_prefix_contract(tmp_path,
|
||||
assert all(m.media == [str(attachment)] for m in extra)
|
||||
assert all("message_thread_id" not in m.metadata for m in extra)
|
||||
|
||||
# Ordinary turns, separate cron runs and tool continuations use the same
|
||||
# system/tools prefix. Per-run instructions and runtime data stay at the end.
|
||||
def stable(row):
|
||||
return json.dumps([row["tools"], row["messages"][0]], ensure_ascii=False)
|
||||
|
||||
@@ -138,7 +132,6 @@ async def test_moved_cron_keeps_reply_send_and_prompt_prefix_contract(tmp_path,
|
||||
@pytest.mark.parametrize("origin", ["websocket", "whatsapp"])
|
||||
@pytest.mark.parametrize("explicit_send", [False, True])
|
||||
async def test_saved_cron_separates_source_chat_from_explicit_recipient(tmp_path, origin, explicit_send):
|
||||
"""Instructions alone do not change routing; a real tool call adds its recipient."""
|
||||
workspace = tmp_path / "workspace"
|
||||
sessions = SessionManager(workspace)
|
||||
bus = MessageBus()
|
||||
@@ -149,7 +142,6 @@ async def test_saved_cron_separates_source_chat_from_explicit_recipient(tmp_path
|
||||
with request_context(RequestContext(origin, chat_id, session_key=session_key)):
|
||||
created = await CronTool(cron).execute(action="add", message=instructions, every_seconds=86400)
|
||||
assert "Created job" in created
|
||||
# The saved binding, not the recipient named in free text, survives a reload.
|
||||
cron = CronService(cron.store_path)
|
||||
job = cron.list_jobs()[0]
|
||||
assert job.payload.session_key == session_key
|
||||
|
||||
@@ -434,7 +434,6 @@ def test_add_job_preserves_origin_delivery_context(tmp_path) -> None:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_heals_runtime_context_from_pending_external_add(tmp_path) -> None:
|
||||
"""Flattened runtime blocks from older action files must not be replayed."""
|
||||
store_path = tmp_path / "cron" / "jobs.json"
|
||||
external = CronService(store_path)
|
||||
job = external.add_job(
|
||||
@@ -923,7 +922,6 @@ async def test_subsecond_job_not_delayed_to_one_second(tmp_path):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_running_service_picks_up_external_add(tmp_path):
|
||||
"""A running service should detect and execute a job added by another instance."""
|
||||
store_path = tmp_path / "cron" / "jobs.json"
|
||||
called: list[str] = []
|
||||
|
||||
@@ -1017,7 +1015,6 @@ async def test_external_update_preserves_run_history_records(tmp_path):
|
||||
|
||||
|
||||
def test_stale_instance_remove_preserves_external_add(tmp_path) -> None:
|
||||
"""A stopped instance must not save a stale snapshot over another instance's job."""
|
||||
store_path = tmp_path / "cron" / "jobs.json"
|
||||
schedule = CronSchedule(kind="every", every_ms=60_000)
|
||||
service_a = CronService(store_path)
|
||||
@@ -1030,7 +1027,6 @@ def test_stale_instance_remove_preserves_external_add(tmp_path) -> None:
|
||||
**_bound_chat("first"),
|
||||
)
|
||||
|
||||
# Prime service_b with a view that does not include later external changes.
|
||||
assert [job.name for job in service_b.list_jobs(include_disabled=True)] == ["first"]
|
||||
|
||||
service_a.add_job(
|
||||
@@ -1046,12 +1042,8 @@ def test_stale_instance_remove_preserves_external_add(tmp_path) -> None:
|
||||
assert [job.name for job in reloaded.list_jobs(include_disabled=True)] == ["second"]
|
||||
|
||||
|
||||
# ── timer race regression tests ──
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_save_store_failure_retries_without_replaying_job(tmp_path, monkeypatch):
|
||||
"""A failed post-run save must be retried before jobs can execute again."""
|
||||
store_path = tmp_path / "cron" / "jobs.json"
|
||||
calls: list[str] = []
|
||||
arm_calls: list[str] = []
|
||||
@@ -1063,8 +1055,6 @@ async def test_save_store_failure_retries_without_replaying_job(tmp_path, monkey
|
||||
service._running = True
|
||||
service._load_store()
|
||||
|
||||
# Spy on _arm_timer so we can assert the scheduler is re-armed even when
|
||||
# the tick fails, without actually scheduling a real timer task.
|
||||
def arm_spy() -> None:
|
||||
arm_calls.append("arm")
|
||||
|
||||
@@ -1094,8 +1084,6 @@ async def test_save_store_failure_retries_without_replaying_job(tmp_path, monkey
|
||||
monkeypatch.setattr(service, "_atomic_write", flaky_atomic_write)
|
||||
await service._on_timer()
|
||||
|
||||
# The failed tick stays alive and retains the advanced in-memory state,
|
||||
# including when a public read would normally reload from disk.
|
||||
assert arm_calls == ["arm"], "scheduler must re-arm after a failed tick"
|
||||
assert service._active_executions == 0
|
||||
assert calls == [job.id]
|
||||
@@ -1104,14 +1092,10 @@ async def test_save_store_failure_retries_without_replaying_job(tmp_path, monkey
|
||||
assert loaded is not None
|
||||
assert loaded.state.last_run_at_ms is not None
|
||||
|
||||
# Manual execution is a second side-effecting entrypoint. It must also
|
||||
# refuse to run until the previous result can be made durable.
|
||||
with pytest.raises(OSError, match="disk full"):
|
||||
await service.run_job(job.id, force=True)
|
||||
assert calls == [job.id]
|
||||
|
||||
# The next healthy tick is reserved for persisting the dirty snapshot. It
|
||||
# must not reload the stale due record or execute the side effect twice.
|
||||
writes_fail = False
|
||||
await service._on_timer()
|
||||
|
||||
@@ -1129,13 +1113,11 @@ async def test_save_store_failure_retries_without_replaying_job(tmp_path, monkey
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_timer_execution_is_not_rolled_back_by_list_jobs_reload(tmp_path):
|
||||
"""list_jobs() during _on_timer should not replace the active store and re-run the same due job."""
|
||||
store_path = tmp_path / "cron" / "jobs.json"
|
||||
calls: list[str] = []
|
||||
|
||||
async def on_job(job):
|
||||
calls.append(job.id)
|
||||
# Simulate frontend polling list_jobs while the timer callback is mid-execution.
|
||||
service.list_jobs(include_disabled=True)
|
||||
await asyncio.sleep(0)
|
||||
|
||||
@@ -1164,9 +1146,6 @@ async def test_timer_execution_is_not_rolled_back_by_list_jobs_reload(tmp_path):
|
||||
assert loaded.state.next_run_at_ms > loaded.state.last_run_at_ms
|
||||
|
||||
|
||||
# ── update_job tests ──
|
||||
|
||||
|
||||
def test_update_job_changes_name(tmp_path) -> None:
|
||||
service = CronService(tmp_path / "cron" / "jobs.json")
|
||||
job = service.add_job(
|
||||
@@ -1336,13 +1315,11 @@ async def test_list_jobs_during_on_job_does_not_cause_stale_reload(tmp_path) ->
|
||||
async def on_job_that_lists(job):
|
||||
nonlocal execution_count
|
||||
execution_count += 1
|
||||
# Simulate the bot calling cron(action=list) mid-execution
|
||||
service.list_jobs()
|
||||
|
||||
service = CronService(store_path, on_job=on_job_that_lists, max_sleep_ms=100)
|
||||
await service.start()
|
||||
|
||||
# Add two jobs scheduled in the past so they're immediately due
|
||||
now_ms = int(time.time() * 1000)
|
||||
for name in ("job-a", "job-b"):
|
||||
service.add_job(
|
||||
@@ -1351,20 +1328,16 @@ async def test_list_jobs_during_on_job_does_not_cause_stale_reload(tmp_path) ->
|
||||
message="test",
|
||||
**_bound_chat(name),
|
||||
)
|
||||
# Force next_run to the past so _on_timer picks them up
|
||||
for job in service._store.jobs:
|
||||
job.state.next_run_at_ms = now_ms - 1000
|
||||
service._save_store()
|
||||
service._arm_timer()
|
||||
|
||||
# Let the timer fire once
|
||||
await asyncio.sleep(0.3)
|
||||
service.stop()
|
||||
|
||||
# Each job should have run exactly once, not looped
|
||||
assert execution_count == 2
|
||||
|
||||
# Verify next_run_at_ms was persisted correctly (in the future)
|
||||
raw = json.loads(store_path.read_text())
|
||||
for j in raw["jobs"]:
|
||||
next_run = j["state"]["nextRunAtMs"]
|
||||
@@ -1414,7 +1387,6 @@ def test_load_jobs_accepts_null_run_history_ms(tmp_path) -> None:
|
||||
|
||||
|
||||
def test_load_jobs_skips_null_run_history_elements(tmp_path) -> None:
|
||||
"""Null runHistory elements must be skipped like LocalTrigger.from_dict."""
|
||||
store_path = tmp_path / "cron" / "jobs.json"
|
||||
store_path.parent.mkdir(parents=True)
|
||||
store_path.write_text(
|
||||
@@ -1510,10 +1482,7 @@ async def test_reregistering_system_job_keeps_pending_every_run(tmp_path, monkey
|
||||
service.stop()
|
||||
|
||||
assert await boot(t0, 120 * minute) == t0 + 120 * minute
|
||||
# A gateway restart before the interval elapses must not push Dream back.
|
||||
assert await boot(t0 + 90 * minute, 120 * minute) == t0 + 120 * minute
|
||||
# A changed interval is a new schedule and is computed from now.
|
||||
assert await boot(t0 + 100 * minute, 60 * minute) == t0 + 160 * minute
|
||||
assert await boot(t0 + 110 * minute, 60 * minute) == t0 + 160 * minute
|
||||
# An overdue interval keeps the existing no-catch-up behavior.
|
||||
assert await boot(t0 + 170 * minute, 60 * minute) == t0 + 230 * minute
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Agent-facing controls for existing scheduled jobs."""
|
||||
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Inspect persisted cron executions through the agent tool."""
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Tests for CronTool._list_jobs() output formatting."""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
@@ -31,9 +29,6 @@ def _bound_chat(chat_id: str = "chat-1") -> dict[str, str]:
|
||||
}
|
||||
|
||||
|
||||
# -- _format_timing tests --
|
||||
|
||||
|
||||
def test_format_timing_cron_with_tz(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
s = CronSchedule(kind="cron", expr="0 9 * * 1-5", tz="America/Denver")
|
||||
@@ -72,13 +67,10 @@ def test_format_timing_at(tmp_path) -> None:
|
||||
|
||||
def test_format_timing_fallback(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
s = CronSchedule(kind="every") # no every_ms
|
||||
s = CronSchedule(kind="every")
|
||||
assert tool._format_timing(s) == "every"
|
||||
|
||||
|
||||
# -- _format_state tests --
|
||||
|
||||
|
||||
def test_format_state_empty(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
state = CronJobState()
|
||||
@@ -129,9 +121,6 @@ def test_format_state_unknown_status(tmp_path) -> None:
|
||||
assert "unknown" in lines[0]
|
||||
|
||||
|
||||
# -- _list_jobs integration tests --
|
||||
|
||||
|
||||
def test_list_empty(tmp_path) -> None:
|
||||
tool = _make_tool(tmp_path)
|
||||
assert tool._list_jobs() == "No scheduled jobs."
|
||||
@@ -194,7 +183,6 @@ async def test_list_shows_last_run_state(tmp_path) -> None:
|
||||
message="test",
|
||||
**_bound_chat(),
|
||||
)
|
||||
# Simulate a completed run by updating state in the store
|
||||
job.state.last_run_at_ms = 1773673200000
|
||||
job.state.last_status = "ok"
|
||||
tool._cron._save_store()
|
||||
@@ -372,7 +360,6 @@ async def test_legacy_zero_interval_job_can_be_listed_repaired_and_removed(tmp_p
|
||||
tool = _make_tool(tmp_path)
|
||||
store_path = tool._cron.store_path
|
||||
store_path.parent.mkdir(parents=True)
|
||||
# Older versions accepted and persisted zero-interval jobs that never ran.
|
||||
store_path.write_text(json.dumps({
|
||||
"version": 1,
|
||||
"jobs": [{
|
||||
@@ -468,7 +455,6 @@ def test_add_job_empty_message_returns_actionable_error(tmp_path) -> None:
|
||||
|
||||
|
||||
def test_add_job_captures_owner_and_origin_without_legacy_delivery_fields(tmp_path) -> None:
|
||||
"""CronTool stores owner/session identity separately from origin delivery context."""
|
||||
tool = _make_tool(tmp_path)
|
||||
meta = {"slack": {"thread_ts": "111.222", "channel_type": "channel"}}
|
||||
with request_context(
|
||||
|
||||
@@ -53,12 +53,10 @@ def registry() -> Iterator[ToolRegistry]:
|
||||
|
||||
class TestSchemaContract:
|
||||
def test_list_accepted_without_message(self, registry: ToolRegistry) -> None:
|
||||
# action='list' must pass schema validation with nothing but 'action'.
|
||||
_, _, err = registry.prepare_call("cron", {"action": "list"})
|
||||
assert err is None
|
||||
|
||||
def test_remove_accepted_without_message(self, registry: ToolRegistry) -> None:
|
||||
# action='remove' must pass schema validation with just 'action' + 'job_id'.
|
||||
_, _, err = registry.prepare_call("cron", {"action": "remove", "job_id": "abc"})
|
||||
assert err is None
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"""Update scheduled tasks through the public tool boundary."""
|
||||
|
||||
from dataclasses import asdict
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
Reference in new issue
Block a user