2145 clonedevicerecord shares empty non nil metadata map between original and clone #2587
No reviewers
Labels
No labels
1week
2weeks
Failed compliance check
IP cameras
NATS
Possible security concern
Review effort 1/5
Review effort 2/5
Review effort 3/5
Review effort 4/5
Review effort 5/5
UI
aardvark
accessibility
amd64
api
arm64
auth
back-end
bgp
blog
bug
build
checkers
ci-cd
cleanup
cnpg
codex
core
dependencies
device-management
documentation
duplicate
dusk
ebpf
enhancement
eta 1d
eta 1hr
eta 3d
eta 3hr
feature
fieldsurvey
github_actions
go
good first issue
help wanted
invalid
javascript
k8s
log-collector
mapper
mtr
needs-triage
netflow
network-sweep
observability
oracle
otel
plug-in
proton
python
question
reddit
redhat
research
rperf
rperf-checker
rust
sdk
security
serviceradar-agent
serviceradar-agent-gateway
serviceradar-web
serviceradar-web-ng
siem
snmp
sysmon
topology
ubiquiti
wasm
wontfix
zen-engine
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
carverauto/serviceradar!2587
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "refs/pull/2587/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from GitHub pull request.
Original GitHub pull request: #2163
Original author: @mfreeman451
Original URL: https://github.com/carverauto/serviceradar/pull/2163
Original created: 2025-12-17T00:12:11Z
Original updated: 2025-12-17T00:18:55Z
Original head: carverauto/serviceradar:2145-clonedevicerecord-shares-empty-non-nil-metadata-map-between-original-and-clone
Original base: staging
Original merged: 2025-12-17T00:18:46Z by @mfreeman451
User description
IMPORTANT: Please sign the Developer Certificate of Origin
Thank you for your contribution to ServiceRadar. Please note, when contributing, the developer must include
a DCO sign-off statement indicating the DCO acceptance in one commit message. Here
is an example DCO Signed-off-by line in a commit message:
Describe your changes
Issue ticket number and link
Code checklist before requesting a review
PR Type
Bug fix, Enhancement, Tests
Description
Core Bug Fixes:
Fixed potential RWMutex deadlock in SNMP service
Checkmethod by removing recursive read lockingFixed host result aliasing in sweep snapshots by implementing deep-copy semantics for
PortResults,PortMap, andICMPStatusFixed SNMP string type conversion error handling with explicit type validation for
ObjectDescriptionandOctetStringMajor Enhancements:
Implemented parameterized SRQL query support across MCP server and all query tools to prevent SQL injection
Added partition-scoped device identifier resolution in identity engine with cache key normalization
Refactored OTEL insert operations with generic callback pattern and extracted SQL templates as constants
Added batch execution helper function
sendBatchExecAllfor consistent error handling across database operationsImplemented Apache AGE Cypher graph query execution support with security checks
Added downsampling functionality for metric time-series queries with configurable aggregation
Added visualization metadata generation for query results with column type and semantic hints
Implemented mutual TLS (mTLS) client certificate authentication support in Rust database layer
Refactored all Rust query modules to support parameterized queries with bind parameter extraction
New Web-NG Foundation:
Established Phoenix LiveView-based web framework with authentication and routing
Integrated Tailwind CSS with daisyUI theme system and custom dark/light mode support
Added custom JavaScript hooks for interactive components (TimeseriesChart, topbar progress)
Implemented Heroicons SVG icon integration via Tailwind CSS plugin
Created Rust NIF module for SRQL query translation to Elixir integration
Docker & Infrastructure:
Enhanced certificate generation with support for extra CNPG certificate IPs and workstation certificates
Updated nginx entrypoint to use web-ng service on port 4000
Testing:
Added comprehensive deep-copy validation tests for host result snapshots
Added parameterized query binding tests for devices, logs, and events
Added SNMP type conversion error handling tests
Added batch operation error handling and execution tests
Added static analysis test to prevent RWMutex deadlock patterns
Added partition-scoped identifier resolution tests
Added poller status upsert validation tests
Diagram Walkthrough
File Walkthrough
41 files
cnpg_observability.go
Refactor OTEL insert operations with generic callback patternpkg/db/cnpg_observability.go
insertOTELRowsfunction with callback-based row handling
otelLogsInsertSQL,otelMetricsInsertSQL,otelTracesInsertSQL)otelRowInserterinterface and type-specific implementations(
otelLogInserter,otelMetricInserter,otelTraceInserter) toencapsulate row data and queuing logic
unitfield tootelMetricsInsertSQLqueryidentity_engine.go
Add partition-scoped device identifier resolutionpkg/registry/identity_engine.go
"::"instead of":"strongIdentifierCacheKeyhelper function to normalize partitionand build cache keys
batchLookupByStrongIdentifiersto group updates bypartition and process each partition separately
groupUpdatesByPartition,collectStrongIdentifierSets, andbatchLookupIdentifierTypeforpartition-scoped lookups
BatchGetDeviceIDsByIdentifiercalls to include partitionparameter
query_utils.go
Implement parameterized SRQL query supportpkg/mcp/query_utils.go
ParameterizedQueryExecutorinterface extendingQueryExecutorwith
ExecuteSRQLQueryWithParamsmethodsrqlBindBuildertype for parameter binding withBindmethodreturning
$NplaceholdersbuildLogQuery,buildRecentLogsQuery,buildDevicesQuery) to return tuples of(string, []any)withparameterized queries
executeSRQLhelper to route queries to parameterized or plainexecutor based on parameter presence
builder.go
Add parameter binding to generic filter builderpkg/mcp/builder.go
FilterHandlerFuncandFilterBuilder.BuildFilterssignatures toaccept
*srqlBindBuilderparameterGenericFilterBuilder.BuildFiltersto use parameter bindinginstead of string concatenation
ordering
BuildGenericFilterToolto createsrqlBindBuilderand pass tofilter handlers
server.go
Migrate MCP server to parameterized queriespkg/mcp/server.go
executeGetDeviceto use parameterized query with$1placeholder
executeQueryEventsto build parameterized queries withsrqlBindBuilderexecuteSRQLQueryWithParamsmethod to route queries toparameterized executor
executeSRQLQueryto delegate toexecuteSRQLQueryWithParamswith empty params
sweep.go
Add HostResult deep-copy functionpkg/models/sweep.go
DeepCopyHostResultfunction that creates a snapshot copy withoutaliasing pointer/slice/map fields
PortResultsslice,PortMapmap, andICMPStatuspointer with proper deep-copying
PortResultsandPortMapin thecopy
tools_sweeps.go
Parameterize sweep tool queriespkg/mcp/tools_sweeps.go
registerGetRecentSweepsToolto use parameterized query forpoller_idfilterregisterGetSweepSummaryToolto use parameterized query forpoller_idfilterexecuteSRQLQueryWithParamsinstead ofexecuteSRQLQuerycnpg_identity_engine.go
Add partition filtering to identifier lookuppkg/db/cnpg_identity_engine.go
batchGetDeviceIDsByIdentifierSQLto include partition filterin WHERE clause
BatchGetDeviceIDsByIdentifierfunction signature to acceptpartitionparametertools_events.go
Parameterize alert tool queriespkg/mcp/tools_events.go
registerGetAlertsToolto use parameterized query forpoller_idfilter
$1placeholder with parameterbinding
executeSRQLQueryWithParamsinstead ofexecuteSRQLQuerypgx_batch_helper.go
Add batch execution helper functionpkg/db/pgx_batch_helper.go
sendBatchExecAllhelper function for executing batch operationswith error handling
ensures proper cleanup
on failure
tools_devices.go
Parameterize device tools queriespkg/mcp/tools_devices.go
$1placeholder
executeSRQLQueryWithParamsinstead ofexecuteSRQLQuerytools_logs.go
Parameterize log tool queriespkg/mcp/tools_logs.go
registerLogToolsto use parameterized query forpoller_idfilter
$1placeholder with parameterbinding
executeSRQLQueryWithParamsinstead ofexecuteSRQLQuerycnpg_unified_devices.go
Use batch helper for device deletion auditpkg/db/cnpg_unified_devices.go
sendBatchExecAllhelperfunction
auth.go
Use batch helper for user storagepkg/db/auth.go
sendBatchExecAllhelperfunction
viz.rs
Add visualization metadata generation for query resultsrust/srql/src/query/viz.rs
results
VizMeta,ColumnMeta,ColumnType,ColumnSemanticstructs fordescribing result columns
meta_for_plan()function that returns visualizationsuggestions and column metadata for different entity types
for columns
downsample.rs
Add downsampling support for metric time-series queriesrust/srql/src/query/downsample.rs
to_sql_and_params()andexecute()functions to build and rundownsampled queries
min, max, sum, count)
types
devices.rs
Refactor devices query to support stats and bind parametersrust/srql/src/query/devices.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
parse_stats_spec()andbuild_stats_query()for count aggregationscollect_filter_params()to extract bind parameters fromdevice filters
services.rs
Refactor services query to support stats and bind parametersrust/srql/src/query/services.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
parse_stats_spec()andbuild_stats_query()for count aggregationscollect_filter_params()to extract bind parameters fromservice filters
parser.rs
Add downsampling and graph cypher entity parsing supportrust/srql/src/parser.rs
GraphCypherentity type for graph database queriesDownsampleSpecandDownsampleAggfor downsamplingconfiguration
bucket,agg, andseriesdownsamplingparameters
as aliassyntax for result aliasinggraph_cypher.rs
Add Apache AGE Cypher graph query execution supportrust/srql/src/query/graph_cypher.rs
database
execute()andto_sql_and_params()functions for runningread-only Cypher queries
injection
interfaces.rs
Refactor interfaces query to support bind parametersrust/srql/src/query/interfaces.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()to extract bind parameters frominterface filters
limit/offset
traces.rs
Refactor traces query to support bind parametersrust/srql/src/query/traces.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()andcollect_text_params()fortrace filter parameters
fields
logs.rs
Refactor logs query to support bind parametersrust/srql/src/query/logs.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()for log filter parameterextraction
operations
cpu_metrics.rs
Refactor CPU metrics query to support bind parametersrust/srql/src/query/cpu_metrics.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()for CPU metric filter parameterextraction
frequency_hz
pollers.rs
Refactor pollers query to support bind parametersrust/srql/src/query/pollers.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()for poller filter parameterextraction
is_healthyfieldotel_metrics.rs
Refactor OTEL metrics query to support bind parametersrust/srql/src/query/otel_metrics.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()for OTEL metric filter parameterextraction
is_slowfielddb.rs
Add mutual TLS (mTLS) client certificate authentication supportrust/srql/src/db.rs
connections
load_client_certs()andload_client_key()functions forcertificate loading
build_client_config()to support mutual TLS (mTLS)authentication
PgConnectionManager::new()to accept optional client cert andkey paths
timeseries_metrics.rs
Refactor timeseries metrics query to support bind parametersrust/srql/src/query/timeseries_metrics.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()for timeseries metric filterparameter extraction
process_metrics.rs
Refactor process metrics query to support bind parametersrust/srql/src/query/process_metrics.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
collect_filter_params()for process metric filterparameter extraction
memory_usage fields
trace_summaries.rs
Refactor trace summaries query to support bind parametersrust/srql/src/query/trace_summaries.rs
to_debug_sql()toto_sql_and_params()returning SQL andbind parameters
bind_param_from_query()to convert SQL bind values toBindParamtypemodels.rs
Add unit field to OTEL metric row modelrust/srql/src/models.rs
unitfield toOtelMetricRowstruct for storing metric unitinformation
into_json()method to include the newunitfield in JSONserialization
disk_metrics.rs
Refactor SQL generation to extract and return bind parametersrust/srql/src/query/disk_metrics.rs
to_debug_sqlfunction toto_sql_and_paramsreturning bothSQL string and bind parameters
collect_text_paramsandcollect_filter_paramshelper functionsto extract filter parameters
limit/offset clauses
collected parameters
memory_metrics.rs
Refactor SQL generation to extract and return bind parametersrust/srql/src/query/memory_metrics.rs
to_debug_sqlfunction toto_sql_and_paramsreturning bothSQL string and bind parameters
collect_text_paramsandcollect_filter_paramshelper functionsto extract filter parameters
limit/offset clauses
collected parameters
device_updates.rs
Refactor SQL generation to extract and return bind parametersrust/srql/src/query/device_updates.rs
to_debug_sqlfunction toto_sql_and_paramsreturning bothSQL string and bind parameters
collect_text_paramswithallow_listsparameter to control listfilter support per field
collect_filter_paramsto handle device-specific filterfields including boolean values
collected parameters
events.rs
Refactor SQL generation to extract and return bind parametersrust/srql/src/query/events.rs
to_debug_sqlfunction toto_sql_and_paramsreturning bothSQL string and bind parameters
collect_text_paramsandcollect_filter_paramshelper functionsto extract filter parameters
limit/offset clauses
collected parameters
lib.rs
Add Rust NIF for SRQL query translation to Elixirweb-ng/native/srql_nif/src/lib.rs
translation
translatefunction as a dirty CPU NIF that converts SRQLqueries to database queries
cases
srql::query::translate_requestfor query processinglib.rs
Export query types and add embedded SRQL supportrust/srql/src/lib.rs
QueryDirection,QueryEngine,QueryRequest,QueryResponse,TranslateRequest, andTranslateResponseEmbeddedSrqlstruct to support embedded SRQL usage withconnection pooling
EmbeddedSrql::newconstructor for initializing withAppConfigschema.rs
Add unit field to events table schemarust/srql/src/schema.rs
unitfield to the events table schema as nullable text columngenerate-certs.sh
Add support for extra CNPG certificate IPs and workstation certdocker/compose/generate-certs.sh
and regenerate if needed
CNPG_CERT_EXTRA_IPSenvironment variable toadd additional IP addresses to CNPG certificate
workstationcertificate for developersconnecting from outside Docker network
regeneration
app.js
Add Phoenix LiveSocket setup and custom hooksweb-ng/assets/js/app.js
TimeseriesCharthook for interactive chart tooltips andhover line visualization
editor integration
router.ex
Add Phoenix router with authentication and LiveView routesweb-ng/lib/serviceradar_web_ng_web/router.ex
protection
endpoints
dashboard pages
logout
9 files
summary_snapshot_test.go
Add snapshot deep-copy verification testspkg/sweeper/summary_snapshot_test.go
TestGetSummary_HostResultsDoNotAliasInternalStateverifyingdeep-copy semantics for host snapshots
TestGetSummary_ConcurrentReadsDoNotPanicensuringconcurrent access to snapshots doesn't panic
ICMPStatusandPortMap/PortResultsare properlydeep-copied and not aliased
parameterized_queries_test.go
Add parameterized query binding testspkg/mcp/parameterized_queries_test.go
TestDevicesGetDeviceBindsDeviceIDverifying device IDparameter binding
TestLogsGetRecentLogsBindsPollerIDverifying poller IDparameter binding
TestEventsGetEventsBindsMappedFiltersverifying multiplefilter parameter binding
TestStructuredToolsRequireParameterizedExecutorensuringnon-parameterized executors are rejected
recordingParameterizedExecutormock to verify query andparameter handling
sweep_deepcopy_test.go
Add deep-copy validation tests for HostResultpkg/models/sweep_deepcopy_test.go
TestDeepCopyHostResult_NoAliasingvalidatingdeep-copy semantics
mutations don't affect source
PortResultsslice,PortMapmap, andICMPStatusare properlydeep-copied
service_deadlock_test.go
Add deadlock prevention static analysis testpkg/checker/snmp/service_deadlock_test.go
TestCheckDoesNotRLockAndCallGetStatususingAST parsing
service.gosource and verifiesCheckmethod doesn't holds.mu.RLockwhile callingGetStatuspgx_batch_helper_test.go
Add batch execution helper testspkg/db/pgx_batch_helper_test.go
TestSendBatchExecAll_EmptyBatchDoesNotSendverifying emptybatches skip execution
TestSendBatchExecAll_ExecErrorIncludesCommandIndexAndClosesverifying error reporting with command index
TestSendBatchExecAll_CloseErrorReturnedWhenExecSucceedsverifying close errors are surfaced
fakeBatchResultsmock to simulate batch execution scenariosclient_conversion_test.go
Add SNMP type conversion testspkg/checker/snmp/client_conversion_test.go
TestConvertVariable_OctetStringBytesverifying[]byteconversion to string
TestConvertVariable_ObjectDescriptionBytesverifying[]byteconversion for object descriptions
TestConvertVariable_StringTypesUnexpectedValueDoNotPanicverifying error handling for unexpected types
pgx_batch_behavior_test.go
Add batch operation error handling testspkg/db/pgx_batch_behavior_test.go
TestInsertEvents_SurfacesBatchInsertErrorsverifying batchinsert error propagation
TestStoreBatchUsers_SurfacesBatchInsertErrorsverifyinguser batch error handling
fakePgxExecutorandfakeBatchResultsmocks to simulate batchfailures
identity_engine_partition_test.go
Add partition-scoped identifier resolution testpkg/registry/identity_engine_partition_test.go
TestBatchLookupByStrongIdentifiers_PartitionScopedverifying partition-scoped identifier resolution
IDs for same MAC address
BatchGetDeviceIDsByIdentifieris called withcorrect partition parameter
cnpg_registry_test.go
Add poller status upsert validation testpkg/db/cnpg_registry_test.go
TestUpsertPollerStatusSQL_PreservesRegistrationMetadataverifying upsert query structure
on conflict
last_seen,is_healthy, andupdated_atare updated4 files
client.go
Fix SNMP string type conversion error handlingpkg/checker/snmp/client.go
ObjectDescriptionandOctetStringfrom conversion map tohandle them separately
convertObjectDescriptionandconvertOctetStringto return(interface{}, error)and validate[]bytetypetypes
checks before map lookup
memory_store.go
Use deep-copy for host result snapshotspkg/sweeper/memory_store.go
convertToSliceto useDeepCopyHostResultinstead of shallowcopy
buildSummaryto useDeepCopyHostResultfor host snapshotsInMemoryStoreand initialization forconsistency
base_processor.go
Use deep-copy for processor host snapshotspkg/sweeper/base_processor.go
collectShardSummariesto useDeepCopyHostResultfor hostsnapshots
processShardForSummaryto useDeepCopyHostResultwhen sendinghosts to channel
processTCPResultcallservice.go
Fix potential RWMutex deadlock in Check methodpkg/checker/snmp/service.go
s.mu.RLock()anddefer s.mu.RUnlock()fromCheckmethodGetStatusperforms itsown locking
write-preferring semantics
4 files
mock_db.go
Update mock for partition-scoped identifier lookuppkg/db/mock_db.go
BatchGetDeviceIDsByIdentifiermock signature to includepartitionparameterregistry_test.go
Update registry tests for partition parameterpkg/registry/registry_test.go
BatchGetDeviceIDsByIdentifiermock expectations to includepartition parameter
allowCanonicalizationQueries,TestProcessBatchDeviceUpdates_MergesSweepIntoCanonicalDevice, andother test functions
canon_simulation_test.go
Update DIRE simulation test for partition keyspkg/registry/canon_simulation_test.go
setupDIREMockDBto usestrongIdentifierCacheKeyfor cache keygeneration
BatchGetDeviceIDsByIdentifierto accept partitionparameter
UpsertDeviceIdentifiersmock to usestrongIdentifierCacheKeyinterfaces.go
Update Service interface for partition parameterpkg/db/interfaces.go
BatchGetDeviceIDsByIdentifierinterface signature to includepartitionparameter1 files
server_test.go
Fix test file indentationpkg/mcp/server_test.go
2 files
entrypoint-nginx.sh
Update nginx entrypoint to use web-ng servicedocker/compose/entrypoint-nginx.sh
webon port 3000 toweb-ngon port4000
coreservice on port 8090app.css
Configure Tailwind CSS with daisyUI and custom themesweb-ng/assets/css/app.css
files
configurations
mode
3 files
daisyui-theme.js
Add daisyUI theme plugin bundle for UI stylingweb-ng/assets/vendor/daisyui-theme.js
themes
and design tokens
modes
topbar.js
Add topbar progress bar libraryweb-ng/assets/vendor/topbar.js
navigation
effects
animation behavior
heroicons.js
Add Heroicons Tailwind CSS pluginweb-ng/assets/vendor/heroicons.js
solid, mini, micro)
101 files
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/2163#issuecomment-3662998200
Original created: 2025-12-17T00:13:41Z
You are nearing your monthly Qodo Merge usage quota. For more information, please visit here.
PR Compliance Guide 🔍
Below is a summary of compliance checks for this PR:
SRQL injection risk
Description: User-controlled
params.Filteris appended directly into the SRQLWHEREconditions withoutbinding/sanitization, allowing crafted input (e.g.,
"x' OR '1'='1") to alter querysemantics if
Filteroriginates from external requests. query_utils.go [83-90]Referred Code
🎫 #2145
cloneDeviceRecordinpkg/registry/device_store.goto deep-copyMetadataeven when itis an empty-but-non-nil map, so clones do not share the underlying map with the source
record.
Metadatadoes not mutate the original stored record’sMetadata(defensive copy / snapshot isolation).Metadatamap cloning scenario (and that theypass).
Codebase context is not defined
Follow the guide to enable codebase context checks.
Generic: Meaningful Naming and Self-Documenting Code
Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting
Status: Passed
Generic: Secure Error Handling
Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.
Status: Passed
Generic: Secure Logging Practices
Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.
Status: Passed
Generic: Robust Error Handling and Edge Case Management
Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation
Status:
Silent lookup failure: Batch identifier lookup errors are silently swallowed by returning an empty match map
without logging or propagating context, making failures hard to detect and debug.
Referred Code
Generic: Comprehensive Audit Trails
Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.
Status:
Audit logging unclear: The new generic OTEL insert path centralizes write operations but does not visibly add or
ensure audit-context logging (e.g., actor/user ID and outcome), which may be required for
critical actions depending on how these inserts are triggered.
Referred Code
Generic: Security-First Input Validation and Data Handling
Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities
Status:
Mixed param enforcement: The new parameter-binding support improves injection safety, but because some paths can
still execute non-parameterized SRQL when
paramsis empty, a human review is needed toconfirm all externally influenced filters are consistently bound (especially in
unprocessed files and other tools).
Referred Code
Compliance status legend
🟢 - Fully Compliant🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/2163#issuecomment-3663000459
Original created: 2025-12-17T00:14:43Z
You are nearing your monthly Qodo Merge usage quota. For more information, please visit here.
PR Compliance Guide 🔍
Below is a summary of compliance checks for this PR:
SRQL injection
Description:
buildLogQueryappendsparams.Filterdirectly into the SRQLWHEREclause without parameterbinding or validation, allowing crafted filter text (e.g.,
... OR 1=1 ...) to alter querysemantics despite other parameters being bound. query_utils.go [83-100]
Referred Code
🎫 #2145
cloneDeviceRecordinpkg/registry/device_store.goso that whensrc.Metadatais anempty but non-nil map, the clone gets its own independent (deep-copied) map rather than
sharing the original map reference.
Metadatacannot affect the original storedDeviceRecord(defensive copy semantics).Metadatamap case to prevent regressions.Codebase context is not defined
Follow the guide to enable codebase context checks.
Generic: Meaningful Naming and Self-Documenting Code
Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting
Status: Passed
Generic: Security-First Input Validation and Data Handling
Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities
Status:
Unvalidated filter injection:
buildLogQuerydirectly appendsparams.Filterinto the SRQL WHERE clause without validationor parameter binding, reintroducing injection risk despite other parameterization changes.
Referred Code
Generic: Comprehensive Audit Trails
Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.
Status:
Audit scope unclear: The PR adds new query execution paths (including parameterized execution) but the diff
does not show whether these critical query actions are audited with user identity,
timestamp, and outcome.
Referred Code
Generic: Robust Error Handling and Edge Case Management
Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation
Status:
Error silently dropped: Database lookup errors in
batchLookupIdentifierTypeare swallowed by returning an emptymap without logging or surfacing context, which can hide partial failures and complicate
debugging.
Referred Code
Generic: Secure Error Handling
Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.
Status:
Potential user-facing detail: The handler returns raw execution errors (wrapped) which may expose backend implementation
details depending on how MCP tool errors are presented to end users.
Referred Code
Generic: Secure Logging Practices
Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.
Status:
Logs include identifier: The tool logs user-supplied
device_idwhich could be sensitive in some deployments andshould be assessed against logging policy/redaction requirements.
Referred Code
Compliance status legend
🟢 - Fully Compliant🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/2163#issuecomment-3663002544
Original created: 2025-12-17T00:15:27Z
PR Code Suggestions ✨
Latest suggestions up to
19d46a5Strengthen slice aliasing regression test
Strengthen the slice aliasing test by adding assertions to verify that appending
to a cloned slice does not affect the original record or other clones.
pkg/registry/device_store_test.go [108-136]
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly points out a significant weakness in the new test case, as it doesn't verify the most critical aspects of the fix: that the original object is not mutated and that clones are isolated from each other. Applying this suggestion makes the regression test substantially more robust.
Make metadata cloning test stricter
Make the metadata cloning test stricter by adding assertions to ensure cloned
maps are not nil and to verify that mutations on one clone do not affect
another.
pkg/registry/device_store_test.go [81-106]
Suggestion importance[1-10]: 6
__
Why: The suggestion improves the test's robustness by adding a check for non-nil maps to prevent potential panics and by adding a symmetric check for clone-to-clone isolation, making the test more thorough.
Previous suggestions
Suggestions up to commit
990a438PR contains many unrelated changes
The PR is a large, monolithic submission containing many unrelated features and
does not include the specific bug fix for
cloneDeviceRecordthat is described inthe linked ticket.
Solution Walkthrough:
Before:
After:
Suggestion importance[1-10]: 10
__
Why: This suggestion is critically important as it correctly identifies that the PR is a massive, multi-feature submission that completely fails to address the specific bug described in the linked ticket.
Fix parameter counting logic bug
Fix a logic flaw in
count_debug_binds_listthat causes it to miscount parametersby removing an incorrect reset of the
in_itemflag.rust/srql/src/query/mod.rs [363-457]
Suggestion importance[1-10]: 8
__
Why: This suggestion correctly identifies a subtle but critical bug in a new debug utility function that would cause incorrect parameter counting and lead to failing tests, and it provides the correct one-line fix.
Fix deep copy logic bug
In
DeepCopyHostResult, prevent appending todst.PortResultswhile iteratingsrc.PortMapto ensure thePortResultsslice is a true deep copy of the sourceand not altered by the map's contents.
pkg/models/sweep.go [203-233]
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies a bug where
dst.PortResultsis mutated while iteratingsrc.PortMap, which is incorrect for a deep copy function. The fix prevents this mutation, ensuring the copiedPortResultsslice is a faithful snapshot of the source.Fix error message formatting
Correct the formatting string in the
anyhow!macro to properly display theexpectedandcurrentbind counts in the error message.rust/srql/src/query/mod.rs [302-304]
Suggestion importance[1-10]: 5
__
Why: The suggestion correctly fixes a formatting error in a debug assertion message, which improves debuggability by ensuring the error message is rendered correctly.
Fix bind count mismatch formatting
Correct the formatting string in the
anyhow!macro to properly displaybind_countandparams.len()in the error message.rust/srql/src/query/devices.rs [76-80]
Suggestion importance[1-10]: 5
__
Why: The suggestion correctly fixes a formatting error in a debug assertion message, which improves debuggability by ensuring the error message is rendered correctly.
Correct error message formatting
Correct the formatting string in the
anyhow!macro to properly displaybind_countandparams.len()in the error message.rust/srql/src/query/services.rs [71-75]
Suggestion importance[1-10]: 5
__
Why: The suggestion correctly fixes a formatting error in a debug assertion message, which improves debuggability by ensuring the error message is rendered correctly.
Improve inconsistent boolean value parsing
Expand boolean parsing for
availableandis_availableto also accept "yes" as atrue value, improving consistency with other modules.
rust/srql/src/query/device_updates.rs [192-197]
Suggestion importance[1-10]: 4
__
Why: The suggestion correctly identifies an inconsistency in boolean string parsing compared to other parts of the codebase. Applying this change improves consistency and user experience, though a better change would be to use the shared
parse_boolfunction.Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/2163#issuecomment-3663004427
Original created: 2025-12-17T00:16:18Z
You are nearing your monthly Qodo Merge usage quota. For more information, please visit here.
PR Code Suggestions ✨
Explore these optional code suggestions:
Improve Cypher query security check
Refactor the
ensure_read_onlyfunction to correctly parse Cypher queries,ignoring keywords within string literals and comments to prevent false
positives.
rust/srql/src/query/graph_cypher.rs [104-126]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a bug in the
ensure_read_onlyfunction that would reject valid queries, and provides a more robust implementation that correctly handles string literals and comments.Avoid placeholder replacement within strings
Update
rewrite_placeholdersto avoid replacing?characters that appear insidestring literals, preventing the generation of incorrect SQL.
rust/srql/src/query/downsample.rs [508-521]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies a bug where
?inside string literals would be incorrectly replaced, and provides a fix that makes the function aware of string context, preventing invalid SQL generation.Fix bug in debug bind counter
Fix a bug in the
count_debug_binds_listfunction to correctly count all items inthe debug output list.
rust/srql/src/query/mod.rs [363-457]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies a bug in the debug-only helper function
count_debug_binds_listand provides a corrected implementation, improving the reliability of debug assertions.Handle non-UTF-8 SNMP strings safely
Validate that the SNMP
ObjectDescriptionis a printable ASCII string beforeconverting; otherwise, return a hex representation to prevent data corruption
from invalid UTF-8 sequences.
pkg/checker/snmp/client.go [273-280]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 6
__
Why: The suggestion correctly identifies that SNMP strings may not be valid UTF-8 and proposes a robust fallback to hex encoding, which prevents potential data corruption.
Populate returned filter map
Populate the
responseFiltersmap with the filters that have been applied to thequery.
pkg/mcp/builder.go [178-182]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that the
responseFiltersmap is not being populated, which is a bug that prevents applied filters from being reflected in the API response.Check context cancellation
Add a check for context cancellation inside the row processing loop to allow for
early termination.
pkg/db/cnpg_observability.go [237-244]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 7
__
Why: The suggestion correctly points out the lack of context cancellation handling in a potentially long-running loop, improving the responsiveness and resource management of the application.
Use standardized boolean parsing
Replace custom boolean parsing logic with a standardized
parse_boolhelper toensure consistent behavior and proper error handling for invalid inputs.
rust/srql/src/query/device_updates.rs [192-197]
[To ensure code accuracy, apply this suggestion manually]Suggestion importance[1-10]: 5
__
Why: The suggestion correctly identifies inconsistent and overly permissive boolean parsing logic and proposes using a stricter, more robust approach, which improves code quality and consistency.
Imported GitHub PR comment.
Original author: @qodo-code-review[bot]
Original URL: https://github.com/carverauto/serviceradar/pull/2163#issuecomment-3663006861
Original created: 2025-12-17T00:17:17Z
Persistent suggestions updated to latest commit
19d46a5