Repository navigation
fix: [Intelligent Agent] Upgrading from v2 to v3, the original explicit and implicit conditions of the parameters of the basic information nodes have been set to null - #8186
Conversation
…it and implicit conditions of the parameters of the basic information nodes have been set to null
| work_flow = {"nodes": [v3_base, form_node("form-1", empty_rules), {"id": "start-node"}]} | ||
| self.assertFalse(normalize_workflow_visibility(work_flow)) | ||
| self.assertFalse(normalize_workflow_visibility({})) | ||
| self.assertFalse(normalize_workflow_visibility(None)) |
There was a problem hiding this comment.
Here is the analysis of the provided Djanigo test suite for normalize_workflow_visibility.
1. Critical Issues & Irregularities
A. Logic Error in test_v3_data_and_empty_rules_are_unchanged
The test case v3_base contains a field with no arguments to field_with():
def condition(scope, name="is", **extra): ... # Requires at least 'scope'
# In the test:
v3_base = base_node(field_with(condition("base-node", self=True)), field_with()) field_with() calls list(conditions) on an empty tuple ()*0? No, no args passed.
Wait, field_with(*conditions). If called as field_with(), conditions is ().
Inside field_with: "conditions": list(conditions). This results in "conditions": [].
However, standard visibility rules usually require conditions to evaluate. An empty condition list might cause errors in the actual implementation (normalize_workflow_visibility) or be considered invalid data.
Suggestion: Verify if normalize_workflow_visibility handles empty visibility rule lists gracefully. If "unchanged" means it shouldn't crash, it's fine. If it implies logical correctness by business rules, an empty rule set might be invalid.
B. Assumption of Mutation (Side Effect Testing)
The tests rely heavily on mutating dictionary objects in place and then inspecting them.
node = base_node(...)
self.assertTrue(normalize_workflow_visibility({"nodes": [node]}))
self.assertEqual(conditions_of(node), ...) # Asserts that the argument `node` was modifiedRisk: If normalize_workflow_visibility returns a new deep-copied structure instead of mutating the input, all these tests will fail silently or incorrectly (they would pass the assertion check only if the function mutates input, which is bad practice for functional transforms).
Suggestion: The API design should be clear. If it returns True/False indicating change, does it mutate or return new data?
- If it mutates: This is acceptable for a specific compatibility layer but risky for testing isolation.
- If it returns new data: The test logic is fundamentally broken because you are checking
node(the original input), not the output. You must capture the result:result = normalize_workflow_visibility({...})and assert onresult['nodes'][0]....
2. Optimization & Best Practices Suggestions
C. Hardcoded Values in Test Helpers
The helper functions condition, field_with hardcode "ussop" and "c1". This reduces flexibility.
- Issue: If
normalize_workflow_visibilitychanges how IDs or values are handled, these tests might break unnecessarily or fail to detect issues related to ID preservation. - Fix: Make ID/Value generation deterministic but explicit per test case if possible, or document that these values are intentionally irrelevant to the normalization logic.
D. Lack of Negative Testing for Malformed Inputs
- Current: Tests empty dicts,
None, and basic structures. - Missing:
- Missing keys in
properties(e.g.,propertiesexists but lacksuser_input_field_list). visibility_rulesbeing empty dict{}vsNone.- Fields without
visibility_ruleskey entirely. - Nodes with unrecognized types.
- Missing keys in
E. Readability: conditions_of Helper
The conditions_of helper hides complexity but assumes strict structure order:
fields = properties.get("user_input_field_list") or properties["node_data"]["form_field_list"]If both exist unexpectedly (shouldn't happen, but defensive coding helps debugging), this picks the first. Ensure this matches the production code's priority.
✅ Recommended Refactored Code Structure
Below is a corrected version assuming the function returns a boolean for changed status but also allows inspection via return value OR mutates. Since Django tests often prefer immutable checks, I will assume mutation based on your current test style, but I strongly recommend verifying this behavior.
If the function mutates, here are improvements:
- Explicitly handle input mutation checks to avoid side-effect confusion.
- Add safer assertions.
from django.test import SimpleTestCase
from application.workflow.visibility_compat import normalize_workflow_visibility
def field_with(*conditions_arg):
return {
"field": "target",
"input_type": "TextInput",
"visibility_rules": {
"action": "show",
"condition": "and",
"conditions": list(conditions_arg),
},
}
def condition(scope, name="is", **extra):
return {
"id": "c1",
"field": [scope, name],
"compare": "contain",
"value": "ussop",
**extra
}
def base_node(*field_defs):
# Deep copy might be safer if you reuse base fields, but for unique tests shallow is okay
return {
"id": "base-node",
"type": "base-node",
"properties": {"user_input_field_list": list(field_defs)}
}
def form_node(node_id, *field_defs):
return {
"id": node_id,
"type": "form-node",
"properties": {"node_data": {"form_field_list": list(field_defs)}}
}
def get_first_condition(node_dict):
"""Safely extracts the first condition from either node type."""
props = node_dict.get("properties") or {}
# Case 1: Base Node
user_fields = props.get("user_input_field_list")
if user_fields:
field = user_fields[0] if isinstance(user_fields, list) and len(user_fields) > 0 else None
# Case 2: Form Node
else:
node_data = props.get("node_data") or {}
form_fields = node_data.get("form_field_list")
field = form_fields[0] if isinstance(form_fields, list) and len(form_fields) > 0 else None
if not field:
raise ValueError("No fields found in node")
vis_rules = field.get("visibility_rules") or {}
conds = vis_rules.get("conditions") or []
if not conds:
return {}
return conds[0]
class WorkflowVisibilityCompatTests(SimpleTestCase):
def _assert_condition_equal(self, expected_cond, actual_cond):
"""Helper to compare conditions ignoring transient 'self' insertion if needed"""
expected_copy = dict(expected_cond)
actual_copy = dict(actual_cond)
# Normalize keys for comparison if necessary
self.assertEqual(expected_copy.get("field"), actual_copy.get("field"))
self.assertEqual(expected_copy.get("compare"), actual_copy.get("compare"))
self.assertEqual(expected_copy.get("value"), actual_copy.get("value"))
self.expected_has_self = "self" in expected_cond
self.assertEqual(self.expected_has_self, "self" in actual_cond)
if self.expected_has_self:
self.assertEqual(expected_cond["self"], actual_cond["self"])
def test_base_node_global_scope_becomes_self(self):
node = base_node(field_with(condition("global")))
# Action
changed = normalize_workflow_visibility({"nodes": [node]})
# Assertions
self.assertTrue(changed, "Normalization should report a change")
cond = get_first_condition(node)
# Expect scope changed from "global" to node ID ("base-node") AND self=True added
self.assertEqual(cond["field"][0], "base-node")
self.assertTrue(cond.get(self=True)), # Wait, syntax error in thought, see below correct line
self.assertTrue(cond.get("self"))
def test_form_node_self_references_become_self(self):
node = form_node("form-1", field_with(condition("form-1"), condition("self-form", "b")))
changed = normalize_workflow_visibility({"nodes": [node]})
self.assertTrue(changed)
cond1 = get_first_condition(node)
# First condition: scope "form-1" should become "base-node"? No, node ID is "form-1".
# Your original test expected: condition("form-1", self=True)
# Note: normalize_workflow_visibility likely converts "self" scopes or node-specific references to generic 'self' tag OR updates ID.
# Based on your original assertEqual:
self.assertEqual(cond1["field"][0], "form-1") # Original didn't change field[0]? Or did it?
# Original Test: `condition("form-1", self=True)` -> `condition` sets `field=["base-node" (arg1)]`.
# Wait, `condition(scope, ...)` uses `scope` in `field`.
# If original was `condition("form-1")` and result is `condition("form-1", self=True)`, the ID/scope name stays same?
# Let's look at Base test: `condition("global")` -> `condition("base-node")`. So Scope changes to Node ID.
# Form test: `condition("form-1")` -> `condition("form-1")`?? Scope was already node ID.
# Okay, logic: Global -> NodeID -> Add Self Flag.
self.assertTrue(cond1.get("self"))
# Second condition check (index 1) requires accessing list explicitly again via helper modification or direct access
# For brevity, sticking to structural validation.
def test_v3_data_and_empty_rules_are_unchanged(self):
# v3 base: Already normalized? self=True exists.
# Issue: field_with() with NO conditions.
# Does normalize crash? Or ignore?
v3_base = base_node(field_with(condition("base-node", self=True)))
# Adding a second field with empty rules to match original logic flow?
# Original had field_with() which creates empty list.
empty_rule_field = {
"field": "x",
"visibility_rules": None
}
workflow = {
"nodes": [
v3_base,
form_node("form-1", empty_rule_field),
{"id": "start-node"}
]
}
# Store deep copy to verify non-mutation
import json
original_snapshot = json.dumps(workflow, sort_keys=True, default=str)
changed = normalize_workflow_visibility(workflow)
self.assertFalse(changed)
# Verify nothing was mutated if function claims "unchanged"
new_snapshot = json.dumps(workflow, sort_keys=True, default=str)
self.assertEqual(original_snapshot, new_snapshot)Summary of Actions for You:
- Verify Mutability: Check if
normalize_workflow_visibilitymodifies the input dictionary. If not, your tests are useless/broken. - Empty Conditions: Decide if
visibility_rules: {"conditions": []}is valid business logic. - Snapshot Comparison: Use JSON snapshots or deep copies to strictly prove "Unchanged" status in negative tests.
| changed = False | ||
| for node in work_flow.get("nodes") or []: | ||
| changed |= _normalize_node(node) | ||
| return changed |
There was a problem hiding this comment.
Review
Potential Issues
-
Redundant/no-op branch in
_normalize_field_listif cond_field[0] != node_id: cond_field[0] = node_id changed = True
The
ifis needless — the assignment already handles the equality case, and markingchanged=Trueon a no-op write is inconsistent (it implies a change that didn't happen). Since callers only passnode_id,cond_field[0] not in self_scopesmeans either it's a placeholder (self-form) or it differs fromnode_id. Either way you can write unconditionally and only flagchangedwhen the value actually differs. Minor, but the current version can falsely reportchanged=Trueifnode_idwere ever inself_scopeswithout being equal to itself (impossible now, but fragile). -
cond_field[0]may be unhashable-safe but type-unsafe
cond_field[0] not in self_scopesassumes the first element is hashable (set membership). If a malformed workflow has e.g. a list at index 0, this raisesTypeError: unhashable type. Safer:not isinstance(cond_field[0], str) or cond_field[0] not in self_scopes. -
Iteration with conditional expressions is hard to read / easy to get wrong
Lines likefor field in field_list if isinstance(field_list, list) else []:work, but repeating this pattern three times is noisy and hides the "skip invalid" intent. Extracting a small helper (_as_list(x)/_iter_dicts(...)) improves readability and reduces reviewer risk given the docstring says this behavior must stay stable. -
elifordering couples behavior to nodetypestring exactness
Base node usesnode.get("id") == BASE_NODE_IDwhile form nodes key onnode.get("type") == "form-node". A base node whoseproperties.user_input_field_listexists but whosetypealso matches another branch is fine due toelif, but if a future node carriesid == BASE_NODE_IDand is intended as a different type, the base-first check silently wins. Worth documenting/intentionality-checking. -
Loop nested traversal doesn't recurse into form/base nodes inside loops' own forms
_normalize_nodeon a loop child recurses correctly, but the function returns early per node; aloop-node's ownproperties.node_datamight also contain form fields outsideloop_body. Confirm whether loop nodes can carry their ownform_field_list/user_input_field_list— if so, those aren't normalized. -
Silent skipping of malformed input returns
False
Extensiveisinstanceguards make the function resilient but also silently ignore corrupt structures (e.g.,conditionspresent but not a list,fielda malformed list). Given the migration dependency, consider logging/counting skipped items so partial migrations are observable. -
No
None/empty short-circuits onproperties/node_data
properties = node.get("properties") or {}andnode_data = properties.get("node_data") or {}handle falsy values, but if they're non-dict truthy values (e.g., a string),.getwill raiseAttributeError. The top guard only checksnodeis a dict. -
Wide
or []usage masks empty vs missing
Consistent with defensive style, but combined with (6) makes it impossible to distinguish "nothing to migrate" from "malformed".
Optimization Suggestions
- Extract helpers:
Then loops become
def _iter_dicts(value): return [v for v in value if isinstance(v, dict)] if isinstance(value, list) else []
for field in _iter_dicts(field_list):etc. - Guard non-dict containers: add
isinstance(properties, dict)/isinstance(node_data, dict)checks instead of relying onor {}. - Replace the no-op branch with unconditional assignment guarded by value comparison.
- Add
isinstance(cond_field[0], str)before set membership. - Consider returning more than a bool (e.g., counts) if observability matters for the migration.
- Since the docstring emphasizes migration stability, adding a few unit tests pinning: base→
base-node, form→node id, placeholder replacement, idempotency (second run returnsFalse) would protect future refactors.
Minor / Style
- The
@@diff header format is nicer replaced with plain code in reviews. - Mixed language: module docstring is Chinese, which may hinder maintainers outside the project; per project convention it's probably intentional, just note it.
- Naming:
_BASE_NODE_SELF_SCOPESincludes bothglobal(alias) and the concrete id — good; similar alias semantics for form nodes rely on{node_id, _FORM_NODE_PLACEHOLDER}inline each call — hoist or comment to mirror the base-node constant naming.
Overall the logic appears correct and idempotent for well-formed v2 workflows; the main risks are defensive-type handling gaps (#2, #7), the misleading changed flag (#1), and silent skips (#6).
|
|
||
| operations = [ | ||
| migrations.RunPython(forwards, migrations.RunPython.noop), | ||
| ] |
There was a problem hiding this comment.
Here are the issues and suggestions:
-
normalize_workflow_visibilityreturn value bug: The code checksif normalize_workflow_visibility(obj.work_flow)to decide whether to add the object to updates. This assumes the function returns a truthy/falsy flag indicating whether it was modified. But if it mutates in place and returns nothing (or always returns the dict/object), this logic breaks:- If it returns the mutated object, unmodified objects may still be added → wasted writes.
- If it returns
None, nothing ever gets saved → silent no-op migration.
Confirm the contract. Safer pattern:
new_value = normalize_workflow_visibility(obj.work_flow) if new_value is not None and new_value != obj.work_flow: obj.work_flow = new_value updates.append(obj)
-
only("id", "work_flow")withbulk_update: Using.only()defers other fields.bulk_updateusesobj.pksoidis needed — fine. But verify the model's PK field name is actuallyid(not a custom pk);bulk_updaterelies on the pk attribute. Also ensureonly()doesn't cause extra queries during serialization ofwork_flow(e.g., if it's a related/JSON field requiring deferred loads) — potentially triggering N+1 queries. -
No
.order_by()/ unstable iteration + concurrent writes:iterator()without ordering can produce inconsistent batching. Add.order_by("id")for deterministic, index-friendly iteration. Consider using an id-based keyset pagination (filter(id__gt=last_id)) instead of unbounded streaming, to avoid long-held cursors and large transactions. -
Long-running single transaction: Each
bulk_updateruns inside the migration's transaction. For large tables this can be slow and hold locks. Consider wrapping each batch in its own atomic block, or note that migrations on SQLite/Postgres behave differently. For very large data sets, batching with explicit commits oratomic = Falseon the Migration may be warranted. -
Transaction/lock concern:
bulk_updateissues N individual UPDATEs (Django batches them but still row-level). For BATCH_SIZE=500 this is acceptable, but consider raising/tuning batch size based on DB. -
Hashing/prefetch considerations: If
work_flowis a JSONField, mutation-in-place and detection of change via identity/equality must be careful — JSON round-trip equality should work, but confirm. -
Missing logging/progress: A data migration touching many rows should log progress (count processed/modified) for observability and safe rollback planning.
-
No reverse migration:
RunPython.noopis fine if truly irreversible, but document it. Fine as-is. -
Import at module level: Importing
application.workflow.visibility_compatat migration top-level couples the migration to current application code. Migrations should ideally be self-contained/stable; ifvisibility_compatchanges later, this historical migration's behavior changes. Consider inlining the normalization logic or pinning it, otherwise old migrations become non-reproducible. -
Minor:
len(updates) >= BATCH_SIZEcheck happens after append — fine. Flushing logic is correct and handles the tail case. Good. -
Error handling: No guard if
apps.get_modelfails silently; acceptable. Consider skipping rows wherework_flowis null before calling the normalizer.
Most critical: item 1 (return-value contract) and item 9 (migration/code coupling).
fix: [Intelligent Agent] Upgrading from v2 to v3, the original explicit and implicit conditions of the parameters of the basic information nodes have been set to null