metaflow icon indicating copy to clipboard operation
metaflow copied to clipboard

Regression: Overriding project decorator with `MutableFlow.add_decorator`

Open valayDave opened this issue 10 months ago • 5 comments

When we override the @project decorator using MutableFlow.add_decorator, it ends up calling the flow decorator's flow_init twice. Once with statically set values in @project and once with newer values coming from the decorator. When we explicitly call MutableFlow.remove_decorator("project") and then go on to adding the new decorator then everything works perfectly fine.

Why is this a problem: If flow_init is called twice we end up writing multiple tags for project_branch (even when we pass down branch using the config values). This affects the namespace objects get placed in. Running below flow with this command will result in multiple project_branch values in the Run tags.

python flow_mutator_example.py --config-value project '{"branch": "my_branch", "production": true}' run

Minimum reproducible example

"""
Usage:
    # Run with default config (uses values from @project decorator)
    python flow_mutator_example.py run

    # Run with config override (replaces @project decorator values)
    python flow_mutator_example.py --config-value project '{"branch": "my_branch", "production": true}' run
"""

from metaflow import FlowSpec, FlowMutator, step, project, Config


class ReplaceProjectDecorator(FlowMutator):
    """
    A FlowMutator that replaces the @project decorator based on Config values.

    Similar to namespaced_trigger.py, this mutator:
    - Reads config values from a Config object (default name: "project")
    - Extracts branch and production settings from config
    - Overrides the existing @project decorator with new values
    """

    def init(self, *args, **kwargs):
        # Name of Config object to use (default: "project")
        self.config_name = kwargs.get("config_name", "project")

    def pre_mutate(self, mutable_flow):
        """
        pre_mutate is required to modify flow-level decorators like @project.
        The mutate() method can only modify step decorators.
        """
        from metaflow import project

        # Extract config values (same pattern as namespaced_trigger.py)
        config_obj = {}
        for config_name, config_value in mutable_flow.configs:
            if config_name == self.config_name:
                config_obj = config_value
                break

        # Get branch and production settings from config
        project_branch = config_obj.get("branch", None)
        is_production = config_obj.get("production", False)

        # Extract existing @project decorator kwargs
        def _extract_project_decorator():
            for name, qual_name, args, kwargs in mutable_flow.decorator_specs:
                if name == "project":
                    return kwargs
            return None

        project_kwargs = _extract_project_decorator()
        if project_kwargs is None:
            # No @project decorator found, nothing to override
            return

        # Get project name from decorator or config
        project_name = project_kwargs.get("name", config_obj.get("name", None))

        if project_name is None:
            raise Exception(
                "You must set a project name in the @project decorator or in the %s config"
                % self.config_name
            )

        # Remove existing @project decorator and add new one with config values
        # mutable_flow.remove_decorator("project")
        mutable_flow.add_decorator(
            deco_type=project,
            deco_kwargs={
                "name": project_name,
                "branch": project_branch,
                "production": is_production,
            },
            duplicates=mutable_flow.OVERRIDE,  # = 3, replaces existing decorator
        )


@ReplaceProjectDecorator()
@project(name="my_project")  # This will be replaced/enhanced by config values
class FlowMutatorExampleFlow(FlowSpec):
    """
    A simple flow to demonstrate the FlowMutator replacing the project decorator.

    The @project decorator values can be overridden via the "project" Config object.
    """

    # Config object that the FlowMutator reads from
    project = Config("project", default_value={})

    @step
    def start(self):
        from metaflow import current

        print(f"Project name: {current.project_name}")
        print(f"Project branch: {current.branch_name}")
        print(f"Is production: {current.is_production}")
        self.project_name = current.project_name
        self.next(self.end)

    @step
    def end(self):
        print(f"Flow completed in project: {self.project_name}")


if __name__ == "__main__":
    FlowMutatorExampleFlow()


Last Working Version

2.17.0 (It was working as expected)

valayDave avatar Jan 07 '26 21:01 valayDave

I would like to solve the issue, please assign me

aviralgarg05 avatar Feb 21 '26 09:02 aviralgarg05

Hey @aviralgarg05 , I actually dug into this one and had started the work on this PR. Apologies, I should have mentioned it on the Issue. can you please validate the PR instead?

vyagh avatar Feb 21 '26 15:02 vyagh

Just saw the new contribution guidelines so not creating a PR before approval @npow.

point 1 (issue with problem) and point 2 (minimal reproduction of problem) are already covered by the issue. point 3 (rationale): -Root cause is _FlowState.setitem in flowspec.py, it updates _self_data but doesn't clear the _merged_data cache. so when add_decorator(OVERRIDE) writes the filtered dict and reads it back, it gets stale data with the old decorator still in it. both end up active, hence the double flow_init -Fix: self._merged_data.pop(key, None) in setitem -tests added: one that reproduces the exact read-->write->read pattern from the OVERRIDE path, one for consecutive overrides, and one for writes without a prior read (to make sure the pop on an empty cache doesn't break

vyagh avatar Feb 21 '26 15:02 vyagh

Hi @vyagh, @aviralgarg05, are either of you still working on this?

On master (bda5e774) this reproduces: two project_branch tags and flow_init runs twice. The cause looks slightly different from the _merged_data.pop idea: the OVERRIDE branch in MutableFlow.add_decorator assigns a filtered dict through _flow_state[...] = {...}, which only updates _self_data, so _do_add() reads the stale cached merged dict. Clearing the cache in __setitem__ would also let a decorator inherited from a base class come back on the next merge, so the proposal is to delete the key in place (which is what remove_decorator already does). It is a one-line change plus tests, and a branch is ready.

@npow @valayDave is that the direction you want? The PR will be opened once a maintainer confirms the approach. @vyagh, if you would rather take it with this approach, say so and I will step back.

sohailshk avatar Nov 10 '26 07:11 sohailshk

Thanks for checking. I’m not actively working on this anymore, and since you already have a branch ready, please go ahead. I’ll step back to avoid duplicating work.

aviralgarg05 avatar Nov 10 '26 12:11 aviralgarg05