Skip to content

Commit c254985

Browse files
authored
[Cleanup] Compact 17 multi-line comment blocks added by recent PRs (#1961)
Recent bug-fix PRs left behind block comments that narrate the defect they fixed -- four to seven lines of "it used to do X, which caused Y" sitting above a one-line change. That history belongs in the PR description and the commit, not in the source, where it has to be read past on every future visit. Each block is reduced to a single line that keeps the operative reason and drops the archaeology: - # Add completion percentage if loops are running. - # - # current_loop is 1-based and set at the *top* of each - # iteration (hiearchical_swarm.py calls - # update_loop(current_loop + 1)), so dividing by max_loops - # reported 100% before the final loop's agents had run. - # Count loops finished instead: the loop in progress is - # current_loop, so current_loop - 1 are done. + # current_loop is 1-based, so count current_loop - 1 as finished. 17 blocks across 6 files, -72/+17 lines. Scope was picked by blaming every run of three or more consecutive comment lines under swarms/ and keeping only those authored by the last 25 commits on master. Comments only -- no code, control flow, or behaviour is touched. black and ruff clean; test_conversation.py and test_cron_job.py pass (89 passed).
1 parent 8e5d44b commit c254985

6 files changed

Lines changed: 17 additions & 72 deletions

File tree

swarms/structs/agent.py

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2156,10 +2156,7 @@ def run_concurrent_tasks(self, tasks: List[str], *args, **kwargs):
21562156
"""
21572157
try:
21582158
logger.info(f"Running concurrent tasks: {tasks}")
2159-
# Pool is scoped to the call, matching how the rest of the codebase
2160-
# runs concurrent work (heavy_swarm, majority_voting,
2161-
# multi_agent_router). An Agent-level pool would keep idle threads
2162-
# alive for the process lifetime of every agent a swarm builds.
2159+
# Call-scoped pool, as in heavy_swarm: no idle threads per agent.
21632160
with ContextThreadPoolExecutor(
21642161
max_workers=os.cpu_count()
21652162
) as executor:
@@ -2497,10 +2494,7 @@ def _reinitialize_after_load(self) -> None:
24972494
rules=self.rules,
24982495
)
24992496

2500-
# No executor to reinitialize: concurrent work creates its own
2501-
# call-scoped pool. The assignment that used to live here stored an
2502-
# executor the enclosing `with` had already shut down, so anything
2503-
# reading it back would have submitted to a dead pool.
2497+
# Nothing to restore: concurrent work builds its own call-scoped pool.
25042498

25052499
except Exception as e:
25062500
logger.error(f"Error reinitializing components: {e}")
@@ -3362,9 +3356,7 @@ def run_batched(
33623356
Returns:
33633357
List[Any]: List of results from each task execution.
33643358
"""
3365-
# `for task, imgs in zip(...)` rebound the parameter to one image per
3366-
# iteration, so a List[str] field received a bare str -- and with the
3367-
# documented default of imgs=None the zip raised before any task ran.
3359+
# Index imgs rather than zip: zip rebound imgs and raised when it was None.
33683360
if imgs is None:
33693361
return [
33703362
self.run(task=task, *args, **kwargs) for task in tasks
@@ -4127,10 +4119,7 @@ def tool_execution_retry(self, response: any, loop_count: int):
41274119
)
41284120
return
41294121

4130-
# execute_tools re-raises whatever the tool raised, and nothing in the
4131-
# framework raises AgentToolExecutionError, so catching only that type
4132-
# caught nothing. Catch broadly here, which is also what the docstring
4133-
# promises ("Other exceptions: Logs error and retries").
4122+
# Catch broadly: nothing raises AgentToolExecutionError, so that caught nothing.
41344123
attempts = max(1, int(self.tool_retry_attempts or 1))
41354124
last_error: Optional[Exception] = None
41364125

@@ -4149,10 +4138,7 @@ def tool_execution_retry(self, response: any, loop_count: int):
41494138
f"Full traceback: {traceback.format_exc()}"
41504139
)
41514140

4152-
# Attempts exhausted. Raising is what the docstring specifies, and it is
4153-
# the only way the caller learns the tools did not run — returning here
4154-
# left `short_memory` with no Tool Executor entry, so the model saw the
4155-
# call as having produced nothing and carried on as if it had succeeded.
4141+
# Attempts exhausted: raise, or the model reads a silent no-op as success.
41564142
raise AgentToolExecutionError(
41574143
f"Agent '{self.agent_name}' failed to execute tools in loop "
41584144
f"{loop_count} after {attempts} attempt(s): {last_error}"

swarms/structs/agent_rearrange.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -565,10 +565,7 @@ def _run_concurrent_workflow(
565565
f"Agent(s) {missing} not registered in this AgentRearrange instance."
566566
)
567567

568-
# Run agents concurrently
569-
# `img` was accepted and dropped, so a flow step written with a comma
570-
# ("A, B") silently ran without the image while the sequential path
571-
# ("A -> B") forwarded it. The async twin below forwards it too.
568+
# Run agents concurrently, forwarding img; this path used to drop it.
572569
results = run_agents_concurrently(
573570
agents=agents_to_run,
574571
task=self.conversation.get_str(),

swarms/structs/concurrent_workflow.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -410,11 +410,7 @@ def agent_streaming_callback(chunk: str):
410410
output = future.result()
411411
results.append((agent.agent_name, output))
412412
except Exception as e:
413-
# Same failure policy as `_run`. This path used to
414-
# convert every failure into an "Error: ..." string
415-
# regardless, so `on_error="raise"` was silently
416-
# revoked by turning the dashboard on, and the
417-
# failure never reached telemetry either.
413+
# Same failure policy as _run: the dashboard must not revoke on_error.
418414
if self.on_error == "raise":
419415
raise
420416
capture_error(

swarms/structs/conversation.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,11 +163,7 @@ def setup_file_path(self):
163163
extension = (
164164
".json" if self.export_method == "json" else ".yaml"
165165
)
166-
# Under conversations_dir, not the process's working directory:
167-
# a bare relative name dropped conversation_<name>.json wherever
168-
# the program happened to run from, and two conversations sharing
169-
# a name in different directories silently loaded each other's
170-
# history.
166+
# Under conversations_dir, not CWD: same-named conversations must not collide.
171167
self.save_filepath = os.path.join(
172168
self.conversations_dir or get_conversation_dir(),
173169
f"conversation_{self.name}{extension}",

swarms/structs/cron_job.py

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -118,11 +118,7 @@ def __init__(
118118
self.execution_count = 0
119119
self.start_time = None
120120

121-
# Failure accounting. A task that raises must not take the schedule
122-
# down with it, but the failures still have to be visible: the loop
123-
# used to set is_running=False and re-raise, which killed the
124-
# scheduler thread on the first error while run() returned normally,
125-
# so a dead job was indistinguishable from a healthy one.
121+
# Failures stay visible without taking the schedule down.
126122
self.error_count = 0
127123
self.consecutive_errors = 0
128124
self.last_error = None
@@ -139,10 +135,7 @@ def reliability_check(self):
139135
"Agent must be provided during initialization"
140136
)
141137

142-
# An empty string is not "no interval given", it is a bad interval.
143-
# It used to fall through this guard and only surface much later, from
144-
# _run(), as "Interval must be provided during initialization" -- which
145-
# is confusing, because it was provided.
138+
# An empty string is a bad interval, not a missing one: fail here, not in _run().
146139
if (
147140
self.interval is not None
148141
and not str(self.interval).strip()
@@ -395,10 +388,7 @@ def _run_job(self, task: str, **kwargs) -> Any:
395388
try:
396389
logger.debug(f"Executing task for job {self.job_id}")
397390

398-
# Execute the agent. Discriminate on having a run() method, not
399-
# on isinstance(Callable): a plain function is Callable too, so
400-
# that test sent every function down the .run() path and left the
401-
# branch below unreachable.
391+
# Dispatch on having run(), not on Callable: a plain function is Callable too.
402392
runner = getattr(self.agent, "run", None)
403393
if callable(runner):
404394
original_output = runner(task=task, **kwargs)
@@ -548,12 +538,7 @@ def _run_schedule(self):
548538
self.schedule.run_pending()
549539
self.consecutive_errors = 0
550540
except Exception as e:
551-
# Log and keep going. Setting is_running=False and re-raising
552-
# here killed the scheduler thread on the first failed
553-
# execution, so a single transient error (a rate limit, a
554-
# dropped connection) permanently stopped the job -- and
555-
# because _block_forever also loops on is_running, run()
556-
# returned normally and the caller was never told.
541+
# Log and keep going: one failed execution must not kill the scheduler.
557542
self.error_count += 1
558543
self.consecutive_errors += 1
559544
self.last_error = e
@@ -710,9 +695,7 @@ def run_many(
710695
return jobs
711696

712697
try:
713-
# Hold here while the per-job threads do the work. Exit as soon as
714-
# every job has stopped, so a fleet that has given up does not
715-
# leave the caller parked forever.
698+
# Wait while the per-job threads work; exit once every job has stopped.
716699
while any(job.is_running for job in jobs):
717700
time.sleep(1)
718701
except KeyboardInterrupt:

swarms/utils/hierarchical_swarm_dashboard.py

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -199,17 +199,9 @@ def _create_status_panel(self) -> Panel:
199199
status_text.append("RUNTIME: ", style="bold white")
200200
status_text.append(f"{runtime:.2f}s", style="bold green")
201201

202-
# Add completion percentage if loops are running.
203-
#
204-
# current_loop is 1-based and set at the *top* of each iteration
205-
# (hiearchical_swarm.py calls update_loop(current_loop + 1)), so
206-
# dividing by max_loops reported 100% before the final loop's
207-
# agents had run. Count loops finished instead: the loop in
208-
# progress is current_loop, so current_loop - 1 are done.
202+
# current_loop is 1-based, so count current_loop - 1 as finished.
209203
if self.max_loops > 0:
210-
# Once the swarm reports COMPLETED every loop has finished,
211-
# including the last one — otherwise the run would end at
212-
# (max_loops - 1) / max_loops and never show 100%.
204+
# COMPLETED means the final loop finished, so show 100%.
213205
completed_loops = (
214206
self.max_loops
215207
if self.director_status == "COMPLETED"
@@ -246,10 +238,7 @@ def _create_agents_table(self) -> Table:
246238
table.add_column("LOOP", style="bold white", width=8)
247239
table.add_column("STATUS", style="bold white", width=15)
248240
table.add_column("TASK", style="white", width=40)
249-
# OUTPUT takes whatever is left rather than a hardcoded 150, which
250-
# made the table ~250 chars and overflowed almost every terminal.
251-
# ratio=1 lets Rich shrink it to the console; the minimum keeps it
252-
# readable on a narrow one.
241+
# OUTPUT takes the remaining width (ratio=1); a fixed 150 overflowed the terminal.
253242
table.add_column(
254243
"OUTPUT",
255244
style="white",
@@ -357,9 +346,7 @@ def _create_director_panel(self) -> Panel:
357346
# Orders section
358347
director_text.append("CURRENT ORDERS:\n", style="bold white")
359348
if self.director_orders:
360-
# Actually show only the first 5. Without the slice every order
361-
# was rendered and the "... and N more" line below contradicted
362-
# what the panel had just printed.
349+
# Show only the first 5, so the "... and N more" line below is accurate.
363350
for i, order in enumerate(self.director_orders[:5]):
364351
director_text.append(f"{i + 1}. ", style="bold cyan")
365352
director_text.append(

0 commit comments

Comments
 (0)