Skip to content

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

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_form
Nov 26, 2026

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

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

…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))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 modified

Risk: 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 on result['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_visibility changes 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., properties exists but lacks user_input_field_list).
    • visibility_rules being empty dict {} vs None.
    • Fields without visibility_rules key entirely.
    • Nodes with unrecognized types.

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:

  1. Explicitly handle input mutation checks to avoid side-effect confusion.
  2. 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:

  1. Verify Mutability: Check if normalize_workflow_visibility modifies the input dictionary. If not, your tests are useless/broken.
  2. Empty Conditions: Decide if visibility_rules: {"conditions": []} is valid business logic.
  3. Snapshot Comparison: Use JSON snapshots or deep copies to strictly prove "Unchanged" status in negative tests.

@shaohuzhang1
shaohuzhang1 merged commit 4ef0a85 into v3 Nov 26, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the pr@v3@fix_form branch November 26, 2026 09:37
changed = False
for node in work_flow.get("nodes") or []:
changed |= _normalize_node(node)
return changed

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Potential Issues

  1. Redundant/no-op branch in _normalize_field_list

    if cond_field[0] != node_id:
        cond_field[0] = node_id
        changed = True

    The if is needless — the assignment already handles the equality case, and marking changed=True on a no-op write is inconsistent (it implies a change that didn't happen). Since callers only pass node_id, cond_field[0] not in self_scopes means either it's a placeholder (self-form) or it differs from node_id. Either way you can write unconditionally and only flag changed when the value actually differs. Minor, but the current version can falsely report changed=True if node_id were ever in self_scopes without being equal to itself (impossible now, but fragile).

  2. cond_field[0] may be unhashable-safe but type-unsafe
    cond_field[0] not in self_scopes assumes the first element is hashable (set membership). If a malformed workflow has e.g. a list at index 0, this raises TypeError: unhashable type. Safer: not isinstance(cond_field[0], str) or cond_field[0] not in self_scopes.

  3. Iteration with conditional expressions is hard to read / easy to get wrong
    Lines like for 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.

  4. elif ordering couples behavior to node type string exactness
    Base node uses node.get("id") == BASE_NODE_ID while form nodes key on node.get("type") == "form-node". A base node whose properties.user_input_field_list exists but whose type also matches another branch is fine due to elif, but if a future node carries id == BASE_NODE_ID and is intended as a different type, the base-first check silently wins. Worth documenting/intentionality-checking.

  5. Loop nested traversal doesn't recurse into form/base nodes inside loops' own forms
    _normalize_node on a loop child recurses correctly, but the function returns early per node; a loop-node's own properties.node_data might also contain form fields outside loop_body. Confirm whether loop nodes can carry their own form_field_list/user_input_field_list — if so, those aren't normalized.

  6. Silent skipping of malformed input returns False
    Extensive isinstance guards make the function resilient but also silently ignore corrupt structures (e.g., conditions present but not a list, field a malformed list). Given the migration dependency, consider logging/counting skipped items so partial migrations are observable.

  7. No None/empty short-circuits on properties/node_data
    properties = node.get("properties") or {} and node_data = properties.get("node_data") or {} handle falsy values, but if they're non-dict truthy values (e.g., a string), .get will raise AttributeError. The top guard only checks node is a dict.

  8. 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:
    def _iter_dicts(value):
        return [v for v in value if isinstance(v, dict)] if isinstance(value, list) else []
    Then loops become for field in _iter_dicts(field_list): etc.
  • Guard non-dict containers: add isinstance(properties, dict) / isinstance(node_data, dict) checks instead of relying on or {}.
  • 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 returns False) 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_SCOPES includes both global (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),
]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here are the issues and suggestions:

  1. normalize_workflow_visibility return value bug: The code checks if 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)
  2. only("id", "work_flow") with bulk_update: Using .only() defers other fields. bulk_update uses obj.pk so id is needed — fine. But verify the model's PK field name is actually id (not a custom pk); bulk_update relies on the pk attribute. Also ensure only() doesn't cause extra queries during serialization of work_flow (e.g., if it's a related/JSON field requiring deferred loads) — potentially triggering N+1 queries.

  3. 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.

  4. Long-running single transaction: Each bulk_update runs 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 or atomic = False on the Migration may be warranted.

  5. Transaction/lock concern: bulk_update issues 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.

  6. Hashing/prefetch considerations: If work_flow is a JSONField, mutation-in-place and detection of change via identity/equality must be careful — JSON round-trip equality should work, but confirm.

  7. Missing logging/progress: A data migration touching many rows should log progress (count processed/modified) for observability and safe rollback planning.

  8. No reverse migration: RunPython.noop is fine if truly irreversible, but document it. Fine as-is.

  9. Import at module level: Importing application.workflow.visibility_compat at migration top-level couples the migration to current application code. Migrations should ideally be self-contained/stable; if visibility_compat changes later, this historical migration's behavior changes. Consider inlining the normalization logic or pinning it, otherwise old migrations become non-reproducible.

  10. Minor: len(updates) >= BATCH_SIZE check happens after append — fine. Flushing logic is correct and handles the tail case. Good.

  11. Error handling: No guard if apps.get_model fails silently; acceptable. Consider skipping rows where work_flow is null before calling the normalizer.

Most critical: item 1 (return-value contract) and item 9 (migration/code coupling).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant