Skip to content

Commit 014017b

Browse files
Merge pull request #746 from microsoft/security-code-quality-fix
refactor: clean up code across multiple components
2 parents 4a5782a + 55979cd commit 014017b

49 files changed

Lines changed: 105 additions & 208 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

infra/scripts/index_datasets.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def extract_docx_text(docx_bytes):
118118

119119
print("Creating or updating Azure Search index...")
120120
search_index_client = SearchIndexClient(endpoint=ai_search_endpoint, credential=credential)
121-
index_result = search_index_client.create_or_update_index(index=index)
121+
search_index_client.create_or_update_index(index=index)
122122
print(f"Index '{ai_search_index_name}' created or updated successfully.")
123123
except Exception as e:
124124
print(f"Error creating/updating index: {e}")
@@ -163,7 +163,9 @@ def extract_docx_text(docx_bytes):
163163
print("Uploading documents to the index...")
164164
search_client = SearchClient(endpoint=ai_search_endpoint, index_name=ai_search_index_name, credential=credential)
165165
result = search_client.upload_documents(documents=data_list)
166-
print(f"Uploaded {len(data_list)} documents.")
166+
successes = sum(1 for r in result if getattr(r, "succeeded", False))
167+
failures = len(data_list) - successes
168+
print(f"Uploaded documents. Requested: {len(data_list)}, Succeeded: {successes}, Failed: {failures}")
167169
except Exception as e:
168170
print(f"Error uploading documents: {e}")
169171
sys.exit(1)

package-lock.json

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/backend/tests/test_app.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,16 @@ def mock_dependencies(monkeypatch):
8787
def test_input_task_invalid_json():
8888
"""Test the case where the input JSON is invalid."""
8989
headers = {"Authorization": "Bearer mock-token"}
90+
invalid_json = "{invalid: json" # deliberately malformed JSON
9091
response = client.post("/input_task", data=invalid_json, headers=headers)
9192

93+
# Assert that the API responds with a client error for invalid JSON
94+
assert response.status_code == 400
95+
# Optionally, check that an error message is present in the response body
96+
# Adjust these assertions to match the actual error schema if needed
97+
body = response.json()
98+
assert "error" in body or "detail" in body
99+
92100

93101
def test_process_request_endpoint_success():
94102
"""Test the /api/process_request endpoint with valid input."""

src/backend/v4/api/router.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,11 @@ async def start_comms(
7878
message = await websocket.receive_text()
7979
logging.debug(f"Received WebSocket message from {user_id}: {message}")
8080
except asyncio.TimeoutError:
81-
pass
81+
# Ignore timeouts to keep the WebSocket connection open, but avoid a tight loop.
82+
logging.debug(
83+
f"WebSocket receive timeout for user {user_id}, process {process_id}"
84+
)
85+
await asyncio.sleep(0.1)
8286
except WebSocketDisconnect:
8387
track_event_if_configured(
8488
"WebSocketDisconnect",

src/backend/v4/common/services/team_service.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -481,8 +481,6 @@ async def validate_team_search_indexes(
481481
error_msg = "Team configuration references search indexes but no Azure Search endpoint is configured"
482482
self.logger.warning(error_msg)
483483
return False, [error_msg]
484-
else:
485-
return True, []
486484

487485
if not index_names:
488486
self.logger.info(

src/backend/v4/magentic_agents/common/lifecycle.py

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,14 @@ async def open(self) -> "MCPEnabledBase":
8787
# Register agent (best effort)
8888
try:
8989
agent_registry.register_agent(self)
90-
except Exception:
91-
pass
90+
except Exception as exc:
91+
# Best-effort registration; log and continue without failing open()
92+
self.logger.warning(
93+
"Failed to register agent %s in agent_registry: %s",
94+
type(self).__name__,
95+
exc,
96+
exc_info=True,
97+
)
9298

9399
return self
94100

@@ -100,13 +106,25 @@ async def close(self) -> None:
100106
if self._agent and hasattr(self._agent, "close"):
101107
try:
102108
await self._agent.close() # AzureAIAgentClient has async close
103-
except Exception:
104-
pass
109+
except Exception as exc:
110+
# Best-effort close; log failure but continue teardown
111+
self.logger.warning(
112+
"Error while closing underlying agent %s: %s",
113+
type(self._agent).__name__ if self._agent else "Unknown",
114+
exc,
115+
exc_info=True,
116+
)
105117
# Unregister from registry if present
106118
try:
107119
agent_registry.unregister_agent(self)
108-
except Exception:
109-
pass
120+
except Exception as exc:
121+
# Best-effort unregister; log and continue teardown
122+
self.logger.warning(
123+
"Failed to unregister agent %s from agent_registry: %s",
124+
type(self).__name__,
125+
exc,
126+
exc_info=True,
127+
)
110128
await self._stack.aclose()
111129
finally:
112130
self._stack = None
@@ -407,26 +425,26 @@ async def close(self) -> None:
407425
if self._agent and hasattr(self._agent, "close"):
408426
try:
409427
await self._agent.close()
410-
except Exception:
411-
pass
428+
except Exception as exc:
429+
logging.warning("Failed to close underlying agent %r: %s", self._agent, exc, exc_info=True)
412430

413431
# Unregister from registry
414432
try:
415433
agent_registry.unregister_agent(self)
416-
except Exception:
417-
pass
434+
except Exception as exc:
435+
logging.warning("Failed to unregister agent %r from registry: %s", self, exc, exc_info=True)
418436

419437
# Close credential and project client
420438
if self.client:
421439
try:
422440
await self.client.close()
423-
except Exception:
424-
pass
441+
except Exception as exc:
442+
logging.warning("Failed to close Azure AgentsClient %r: %s", self.client, exc, exc_info=True)
425443
if self.creds:
426444
try:
427445
await self.creds.close()
428-
except Exception:
429-
pass
446+
except Exception as exc:
447+
logging.warning("Failed to close credentials %r: %s", self.creds, exc, exc_info=True)
430448

431449
finally:
432450
await super().close()

src/backend/v4/magentic_agents/magentic_agent_factory.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,6 @@ def __init__(self, team_service: Optional[TeamService] = None):
3333
self._agent_list: List = []
3434
self.team_service = team_service
3535

36-
# @staticmethod
37-
# def parse_team_config(file_path: Union[str, Path]) -> SimpleNamespace:
38-
# """Parse JSON file into objects using SimpleNamespace."""
39-
# with open(file_path, 'r') as f:
40-
# data = json.load(f)
41-
# return json.loads(json.dumps(data), object_hook=lambda d: SimpleNamespace(**d))
42-
4336
# Ensure only an explicit boolean True in the source sets this flag.
4437
def extract_use_reasoning(self, agent_obj):
4538
# Support both dict and attribute-style objects

src/backend/v4/magentic_agents/models/agent_models.py

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -36,24 +36,6 @@ def from_env(cls) -> "MCPConfig":
3636
)
3737

3838

39-
# @dataclass(slots=True)
40-
# class BingConfig:
41-
# """Configuration for connecting to Bing Search."""
42-
# connection_name: str = "Bing"
43-
44-
# @classmethod
45-
# def from_env(cls) -> "BingConfig":
46-
# connection_name = config.BING_CONNECTION_NAME
47-
48-
# # Raise exception if required environment variable is missing
49-
# if not connection_name:
50-
# raise ValueError(f"{cls.__name__} Missing required environment variables")
51-
52-
# return cls(
53-
# connection_name=connection_name,
54-
# )
55-
56-
5739
@dataclass(slots=True)
5840
class SearchConfig:
5941
"""Configuration for connecting to Azure AI Search."""
@@ -65,7 +47,6 @@ class SearchConfig:
6547
@classmethod
6648
def from_env(cls, index_name: str) -> "SearchConfig":
6749
connection_name = config.AZURE_AI_SEARCH_CONNECTION_NAME
68-
index_name = index_name
6950
endpoint = config.AZURE_AI_SEARCH_ENDPOINT
7051

7152
# Raise exception if any required environment variable is missing
@@ -76,6 +57,6 @@ def from_env(cls, index_name: str) -> "SearchConfig":
7657

7758
return cls(
7859
connection_name=connection_name,
79-
index_name=index_name,
80-
endpoint=endpoint
60+
endpoint=endpoint,
61+
index_name=index_name
8162
)

src/frontend/frontend_server.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
import html
21
import os
32

43
import uvicorn
54
from dotenv import load_dotenv
65
from fastapi import FastAPI
76
from fastapi.middleware.cors import CORSMiddleware
8-
from fastapi.responses import FileResponse, HTMLResponse
7+
from fastapi.responses import FileResponse
98
from fastapi.staticfiles import StaticFiles
109

1110
# Load environment variables from .env file

0 commit comments

Comments
 (0)