Skip to content

Commit 3a1a3d5

Browse files
committed
fix(security): replace remaining assert statements with proper error handling
Replaced 53 assert statements across 22 files with proper if/raise patterns (TypeError, ValueError, AssertionError) to resolve Bandit B101 alerts.
1 parent 13cbd42 commit 3a1a3d5

22 files changed

Lines changed: 116 additions & 69 deletions

File tree

rdagent/app/data_science/conf.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,5 @@ class DataScienceBasePropSetting(KaggleBasePropSetting):
201201
DS_RD_SETTING = DataScienceBasePropSetting()
202202

203203
# enable_cross_trace_diversity and llm_select_hypothesis should not be true at the same time
204-
assert not (
205-
DS_RD_SETTING.enable_cross_trace_diversity and DS_RD_SETTING.llm_select_hypothesis
206-
), "enable_cross_trace_diversity and llm_select_hypothesis cannot be true at the same time"
204+
if DS_RD_SETTING.enable_cross_trace_diversity and DS_RD_SETTING.llm_select_hypothesis:
205+
raise ValueError("enable_cross_trace_diversity and llm_select_hypothesis cannot be true at the same time")

rdagent/app/finetune/llm/loop.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -58,18 +58,18 @@ def main(
5858

5959
if user_target_scenario:
6060
FT_RD_SETTING.user_target_scenario = user_target_scenario
61-
assert (
62-
FT_RD_SETTING.user_target_scenario is None
63-
), "user_target_scenario is not yet supported, please specify via benchmark and benchmark_description"
61+
if FT_RD_SETTING.user_target_scenario is not None:
62+
raise ValueError("user_target_scenario is not yet supported, please specify via benchmark and benchmark_description")
6463
if upper_data_size_limit:
6564
FT_RD_SETTING.upper_data_size_limit = upper_data_size_limit
6665
logger.info(f"Set upper_data_size_limit to {FT_RD_SETTING.upper_data_size_limit}")
6766
if benchmark and benchmark_description:
6867
FT_RD_SETTING.target_benchmark = benchmark
6968
FT_RD_SETTING.benchmark_description = benchmark_description
70-
assert FT_RD_SETTING.user_target_scenario or (
71-
FT_RD_SETTING.target_benchmark and FT_RD_SETTING.benchmark_description
72-
), "Either user_target_scenario or target_benchmark must be specified for LLM fine-tuning."
69+
if not (
70+
FT_RD_SETTING.user_target_scenario or (FT_RD_SETTING.target_benchmark and FT_RD_SETTING.benchmark_description)
71+
):
72+
raise ValueError("Either user_target_scenario or target_benchmark must be specified for LLM fine-tuning.")
7373

7474
# Update configuration with provided parameters
7575
if dataset:
@@ -82,9 +82,8 @@ def main(
8282
model_target = FT_RD_SETTING.base_model if FT_RD_SETTING.base_model else "auto selected model"
8383

8484
# Temporary assertion until auto-selection is implemented
85-
assert (
86-
FT_RD_SETTING.base_model is not None
87-
), "Base model auto selection not yet supported, please specify via --base-model"
85+
if FT_RD_SETTING.base_model is None:
86+
raise ValueError("Base model auto selection not yet supported, please specify via --base-model")
8887

8988
logger.info(f"Starting LLM fine-tuning on dataset='{data_set_target}' with model='{model_target}'")
9089

rdagent/app/qlib_rd_loop/quant.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ async def direct_exp_gen(self, prev_out: dict[str, Any]):
7878
while True:
7979
if self.get_unfinished_loop_cnt(self.loop_idx) < RD_AGENT_SETTINGS.get_max_parallel():
8080
hypo = self._propose()
81-
assert hypo.action in ["factor", "model"]
81+
if hypo.action not in ["factor", "model"]:
82+
raise ValueError(f"hypo.action must be 'factor' or 'model', got {hypo.action!r}")
8283
if hypo.action == "factor":
8384
exp = self.factor_hypothesis2experiment.convert(hypo, self.trace)
8485
else:

rdagent/components/coder/CoSTEER/__init__.py

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,10 @@ def get_develop_max_seconds(self) -> int | None:
7575

7676
def _get_last_fb(self) -> CoSTEERMultiFeedback:
7777
fb = self.evolve_agent.evolving_trace[-1].feedback
78-
assert fb is not None, "feedback is None"
79-
assert isinstance(fb, CoSTEERMultiFeedback), "feedback must be of type CoSTEERMultiFeedback"
78+
if fb is None:
79+
raise AssertionError("feedback is None")
80+
if not isinstance(fb, CoSTEERMultiFeedback):
81+
raise TypeError("feedback must be of type CoSTEERMultiFeedback")
8082
return fb
8183

8284
def should_use_new_evo(self, base_fb: CoSTEERMultiFeedback | None, new_fb: CoSTEERMultiFeedback) -> bool:
@@ -121,7 +123,8 @@ def develop(self, exp: Experiment) -> Experiment:
121123

122124
for evo_exp in self.evolve_agent.multistep_evolve(evo_exp, self.evaluator):
123125
iteration_count += 1
124-
assert isinstance(evo_exp, Experiment) # multiple inheritance
126+
if not isinstance(evo_exp, Experiment):
127+
raise TypeError("evo_exp must be an instance of Experiment")
125128
evo_fb = self._get_last_fb()
126129
update_fallback = self.should_use_new_evo(
127130
base_fb=fallback_evo_fb,
@@ -154,7 +157,8 @@ def develop(self, exp: Experiment) -> Experiment:
154157
evo_exp = fallback_evo_exp
155158
evo_exp.recover_ws_ckp()
156159
evo_fb = fallback_evo_fb
157-
assert evo_fb is not None # multistep_evolve should run at least once
160+
if evo_fb is None:
161+
raise AssertionError("multistep_evolve should run at least once")
158162
evo_exp = self._exp_postprocess_by_feedback(evo_exp, evo_fb)
159163
except CoderError as e:
160164
e.caused_by_timeout = reached_max_seconds
@@ -264,9 +268,12 @@ def _exp_postprocess_by_feedback(self, evo: Experiment, feedback: CoSTEERMultiFe
264268
- Raise Error if it failed to handle the develop task
265269
-
266270
"""
267-
assert isinstance(evo, Experiment)
268-
assert isinstance(feedback, CoSTEERMultiFeedback)
269-
assert len(evo.sub_workspace_list) == len(feedback)
271+
if not isinstance(evo, Experiment):
272+
raise TypeError("evo must be an instance of Experiment")
273+
if not isinstance(feedback, CoSTEERMultiFeedback):
274+
raise TypeError("feedback must be an instance of CoSTEERMultiFeedback")
275+
if len(evo.sub_workspace_list) != len(feedback):
276+
raise ValueError("Length of sub_workspace_list must match length of feedback")
270277

271278
# FIXME: when whould the feedback be None?
272279
failed_feedbacks = [

rdagent/components/coder/CoSTEER/evolving_strategy.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,8 @@ def evolve_iter(
122122
last_feedback = None
123123
if len(evolving_trace) > 0:
124124
last_feedback = evolving_trace[-1].feedback
125-
assert isinstance(last_feedback, CoSTEERMultiFeedback)
125+
if not isinstance(last_feedback, CoSTEERMultiFeedback):
126+
raise TypeError("last_feedback must be of type CoSTEERMultiFeedback")
126127

127128
# 1.找出需要evolve的task
128129
to_be_finished_task_index: list[int] = []

rdagent/components/coder/CoSTEER/knowledge_management.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1028,7 +1028,8 @@ def graph_query_by_intersection(
10281028
10291029
"""
10301030
node_count = len(nodes)
1031-
assert node_count >= 2, "nodes length must >=2"
1031+
if node_count < 2:
1032+
raise ValueError("nodes length must >=2")
10321033
intersection_node_list = []
10331034
if output_intersection_origin:
10341035
origin_list = []

rdagent/components/coder/model_coder/eva_utils.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,12 @@ def evaluate(
5858
model_execution_feedback: str = "",
5959
model_value_feedback: str = "",
6060
):
61-
assert isinstance(target_task, ModelTask)
62-
assert isinstance(implementation, ModelFBWorkspace)
63-
if gt_implementation is not None:
64-
assert isinstance(gt_implementation, ModelFBWorkspace)
61+
if not isinstance(target_task, ModelTask):
62+
raise TypeError("target_task must be of type ModelTask")
63+
if not isinstance(implementation, ModelFBWorkspace):
64+
raise TypeError("implementation must be of type ModelFBWorkspace")
65+
if gt_implementation is not None and not isinstance(gt_implementation, ModelFBWorkspace):
66+
raise TypeError("gt_implementation must be of type ModelFBWorkspace")
6567

6668
model_task_information = target_task.get_task_information()
6769
code = implementation.all_codes
@@ -113,10 +115,12 @@ def evaluate(
113115
model_value_feedback: str,
114116
model_code_feedback: str,
115117
):
116-
assert isinstance(target_task, ModelTask)
117-
assert isinstance(implementation, ModelFBWorkspace)
118-
if gt_implementation is not None:
119-
assert isinstance(gt_implementation, ModelFBWorkspace)
118+
if not isinstance(target_task, ModelTask):
119+
raise TypeError("target_task must be of type ModelTask")
120+
if not isinstance(implementation, ModelFBWorkspace):
121+
raise TypeError("implementation must be of type ModelFBWorkspace")
122+
if gt_implementation is not None and not isinstance(gt_implementation, ModelFBWorkspace):
123+
raise TypeError("gt_implementation must be of type ModelFBWorkspace")
120124

121125
system_prompt = T(".prompts:evaluator_final_feedback.system").r(
122126
scenario=(

rdagent/components/document_reader/document_reader.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,16 @@ def load_and_process_one_pdf_by_azure_document_intelligence(
8585

8686

8787
def load_and_process_pdfs_by_azure_document_intelligence(path: Path) -> dict[str, str]:
88-
assert RD_AGENT_SETTINGS.azure_document_intelligence_key is not None
89-
assert RD_AGENT_SETTINGS.azure_document_intelligence_endpoint is not None
88+
if RD_AGENT_SETTINGS.azure_document_intelligence_key is None:
89+
raise AssertionError("azure_document_intelligence_key must be set")
90+
if RD_AGENT_SETTINGS.azure_document_intelligence_endpoint is None:
91+
raise AssertionError("azure_document_intelligence_endpoint must be set")
9092

9193
content_dict = {}
9294
ab_path = path.resolve()
9395
if ab_path.is_file():
94-
assert ".pdf" in ab_path.suffixes, "The file must be a PDF file."
96+
if ".pdf" not in ab_path.suffixes:
97+
raise ValueError("The file must be a PDF file.")
9598
proc = load_and_process_one_pdf_by_azure_document_intelligence
9699
content_dict[str(ab_path)] = proc(
97100
ab_path,

rdagent/components/loader/task_loader.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ def __init__(self, path: Path) -> None:
8787
self.path = Path(path)
8888

8989
def load(self, task: ModelTask) -> ModelFBWorkspace:
90-
assert task.name is not None
90+
if task.name is None:
91+
raise AssertionError("task.name should not be None")
9192
mti = ModelFBWorkspace(task)
9293
mti.prepare()
9394
with open(self.path / f"{task.name}.py", "r") as f:

rdagent/oai/backend/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,8 @@ def _try_create_chat_completion_or_embedding( # type: ignore[no-untyped-def]
541541
**kwargs,
542542
) -> str | list[list[float]]:
543543
"""This function to share operation between embedding and chat completion"""
544-
assert not (chat_completion and embedding), "chat_completion and embedding cannot be True at the same time"
544+
if chat_completion and embedding:
545+
raise ValueError("chat_completion and embedding cannot be True at the same time")
545546
max_retry = LLM_SETTINGS.max_retry if LLM_SETTINGS.max_retry is not None else max_retry
546547
timeout_count = 0
547548
violation_count = 0

0 commit comments

Comments
 (0)