Skip to content

refactor(file): Redesign WalkTree for Starlark consumption #248

Open

Description

@David-Noble-at-work

Problem

WalkTree's Reducer signature is designed for Go-side compensable operation chains:

type Reducer func(initial any, resource Resource, relativePath string, stack *op.RecoveryStack) (result any, err error)

This is unusable from Starlark for two reasons:

  1. resource marshals as a full struct — Starlark callers just need a file path, not a file.Resource with SourcePath, Checksum, Size, Mode, etc.
  2. The accumulator pattern is too complex — Starlark scripts want a simple callback, not a fold/reduce with initial and stack.

Proposed Redesign

Unify resource and relativePath into a single source file.Resource parameter. The Resource already contains the path — relativePath is redundant. The new signature:

type Reducer func(initial any, source file.Resource, stack *op.RecoveryStack) (result any, err error)

For Starlark consumption:

  • source should marshal as a path string (the absolute path), not the full struct
  • stack should not be visible to Starlark callers — the framework should suppress it or pass nil
  • The accumulator pattern may need a simpler alternative for scripts that just want per-entry callbacks

Context

  • file.Find was added as a non-callback alternative for recursive file discovery (** patterns)
  • The callable bridge (buildCallableFunc) can marshal Starlark functions to Go functions, so WalkTree could work from Starlark — but the Reducer signature makes it impractical
  • See plan: docs/plans/star-provider-migration.md

Design Analysis (2026-03-26)

Callable contract

Every Starlark callable returns (starlark.Value, error) — one result or an error (via fail()). There is no multi-return. This means:

  • The Go Reducer signature (any, Resource, string, *RecoveryStack) → (any, error) cannot be directly bridged
  • unmarshalReturn in the callable adapter currently handles multi-return Go signatures that Starlark can never produce — the middle-return zero-filling is dead code
  • The honest callable adapter is: call → if error, return it → unmarshal the single value

Two worlds, one action

WalkTree serves two use cases with different constraints:

Go (graph action) Starlark
Reducer signature func(acc any, resource Resource) (any, error) def reducer(acc, resource) -> acc
Error signaling Return error fail("message") → becomes Go error
Resource access Full Resource struct StructValue with path attrs
Compensation Not applicable Not applicable

WalkTree is a FallibleAction, not a CompensableAction

WalkTree is a query — it walks the tree and accumulates a result. It does not mutate. The RecoveryStack and relativePath parameters should be removed from both WalkTree and Reducer:

  • RecoveryStack: mutations belong in downstream graph steps, not inside the walk
  • relativePath: redundant — Resource.SourcePath carries both .Abs() and .Rel() after Resolve

New signatures:

type Reducer func(acc any, resource Resource) (any, error)

func (p *Provider) WalkTree(root Resource, fn Reducer, honorGitignore bool) (any, error)

Mutating operations (writes, copies, moves) should occur downstream from WalkTree as separate graph steps driven by its result value. Those downstream actions are individually compensable through the normal action bridge.

Conclusion

The compensability of a walk is determined by the mutations that follow it, not by the walk itself. The walk accumulates; the graph acts on what was accumulated.

  • Go: Reducer receives (acc, resource) and returns (any, error). Pure accumulation.
  • Starlark: def reducer(acc, resource) -> acc. Same contract, simpler surface.

The adapter wraps the Starlark function into a Go Reducer, marshaling Resource to a StructValue.

Related refactoring

buildCallableFunc, unmarshalReturn, and makeErrorReturn have been moved from marshal.go to callable.go — they are callable-specific, not general marshal utilities. The doc comments and implementation need further tightening to reflect that a callable always returns (starlark.Value, error).

Activity

  1. David-Noble-at-work commented on Oct 1, 2026

    @David-Noble-at-work
    ContributorAuthor

    The signature may not be the problem. Measured 2026-10-01.

    This issue's analysis predates the function.Resource work, and that work already built the bridge it proposes.
    Starlark-to-Go func conversion exists and is reachable. What is missing is one step earlier than the
    Reducer redesign described above.

    What happens today

    Calling file.walk_tree from a linter extension -- the ambient surface, not the plan surface:

    def visit(accumulated, entry, relative_path, stack):
        ...
    file.walk_tree(root=path, fn=visit)
    Error in file.walk_tree: param fn: *starlark.Function value is neither
    assignable nor convertible to file.Reducer
    

    Why, precisely

    op.Convert has ten steps, and step 5 is the bridge:

    //  5. Source-side opt-in -- value implements [SourceConverter] and advertises the target type.
    if c, ok := value.(SourceConverter); ok && c.CanConvertTo(target) {

    function.Resource implements exactly that -- CanConvertTo and ConvertTo, the latter documented as
    "Converts to any Go func type by building a bridge that converts arguments, calls the underlying starlark
    function, and converts the result."
    It validates parameter counts, rejects varargs and kwargs, and accepts
    Go returns of (), (T), (error) or (T, error).

    So the conversion works when the value IS a function.Resource. What arrives from an ambient call is a
    bare *starlark.Function, which implements no SourceConverter, so it falls through all ten steps to
    explainRefusal.

    On the plan surface a lambda is desugared into a content-addressed function.Resource first, which is why
    cmd/devlore-test/devloretest/data/test_function_call_walk_tree.star works:

    walked = plan.file.walk_tree(root=root, fn=collector, include_gitignored=True)

    Its own comment says so: "a lambda desugars to the new function.call action and rides the graph as a
    content-addressed function.Resource."
    Nothing does that wrapping on the ambient path.

    The missing piece is the desugaring, not the signature

    Either op.Convert gains a step that wraps a *starlark.Function in a function.Resource when the target is
    a func type, or the ambient receiver path does that wrapping before calling Convert. Then
    file.walk_tree works from a linter with its signature unchanged.

    That is worth settling before the Reducer redesign this issue proposes, because the redesign is justified
    here by "the accumulator pattern is too complex" and "resource marshals as a full struct" -- and if the only
    real blocker is a missing wrap, those are ergonomics arguments rather than blockers. They may still be worth
    doing; they are a different change from making it work.

    Also stale above: buildCallableFunc no longer exists by that name. Its capability moved into
    function.Resource.ConvertTo and bridgeable, so the sentence "the callable bridge (buildCallableFunc) can
    marshal Starlark functions to Go functions" is still TRUE in substance and wrong in the identifier.

    How this surfaced

    devlore-cli#994 Phase 5 needed one tree traversal instead of 39 file.find calls -- 39 patterns of which 34
    match no file in this repository, measured at 4.3 s warm against 1.1 s with four. file.walk_tree was the
    obvious instrument and refused. The work landed on a single file.find(path + "/**/*") instead, which this
    issue itself names as the sanctioned alternative: "file.Find was added as a non-callback alternative for
    recursive file discovery."
    Measured equivalent -- 1,016 files both ways, 4.3 s to 0.91 s warm -- so #994 is
    not blocked. But a linter that wants to fold over a tree still cannot.

    Related: #945 (the traversal surface has no link predicate) and #170 (closed; the same problem seen from the
    binding generator's side, and its closing note already said "the reflection bridge needs to support
    starlark.Callable as a parameter type").

  2. David-Noble-at-work commented on Oct 1, 2026

    @David-Noble-at-work
    ContributorAuthor

    Researched exhaustively 2026-10-01. The marshaling question is settled, and the fix proposed in March does not work

    Fourteen agents, every claim below traced to source rather than inferred. Two conclusions, and the second
    kills the approach this issue has been carrying.

    1. *op.RecoveryStack marshals into Starlark. file.Reducer does NOT need a new signature

    The doubt that blocked this -- "a script has no business seeing a RecoveryStack, so the signature must
    change" -- does not fire. The chain, read end to end:

    function.resource.ConvertTo builds reflect.MakeFunc(target, ...) and unwraps each argument with
    arg.Interface() (pkg/op/provider/function/resource.go:695-701) -> invoker.CallStarlark converts each
    argument via converter.toStarlark (pkg/op/starlarkbridge/invoker.go:79-89) -> toStarlark falls through
    to toStarlarkReflect (go_receiver.go:342-353) -> elem() dereferences the non-nil pointer to an
    addressable struct (go_receiver.go:413) -> structToStarlark takes rv.Addr() and resolves a receiver type
    (go_receiver.go:739-770).

    The derive cannot fail: TypeByReflectionOrDerive falls back to NewReceiverType(t, nil) on error
    (receiver_registry.go:679-690), which routes to derivedMethods, which skips an unclassifiable method
    rather than aborting -- and its own doc comment names RecoveryStack.ResultByUnitID as the case
    (receiver_type.go:535-578). structToStarlark's comment at :726-731 names "a framework type like
    *op.RecoveryStack handed to a reducer" as its motivating example. Pointer identity survives via rv.Addr(),
    so the reducer sees the live stack.

    Shape also passes: file.Reducer is 4-in/2-out with error last (provider.go:2565), so both
    resource.go:637 (NumParams == NumIn) and resource.go:675-684 (hasError, numValues <= 1) accept it.

    Keeping the 4-parameter shape also keeps all five existing .star fixtures valid. Changing arity breaks
    every one with no escape hatch, because resource.go:637-645 refuses a count mismatch and refuses *args and
    **kwargs outright.

    2. Wrapping the callable in a function.Resource cannot work

    This was the plan. It fails for two independent reasons.

    It is a snapshot, not a bridge. synthesize emits only fn.NumFreeVars() bindings plus the def text
    (synthesize.go:41-82), and compileSource resolves with isPredeclared hard-wired to
    func(string) bool { return false } (resource.go:952-958). Checked against starlark-go's resolver rather
    than assumed: a reference reaching the file block returns Global/Predeclared/Universal, and a FreeVar is
    created only for a Local/Free/Cell binding of an enclosing function (resolve/resolve.go:954-996,
    useToplevel at :415-454). So a top-level def reading a module-level variable has NumFreeVars() == 0,
    nothing is emitted, and the synthesized program fails with undefined: <name>.

    Not hypothetical. cmd/devlore-test/devloretest/data/test_walk_tree_closure.star:17-24 sets ext = ".py" at
    module level and reads it inside def filter_by_ext(...). That fixture cannot work through the archival
    path in either immediate or plan mode.
    A real linter reducer is worse:
    com.noblefactor.star.LintCopyright/commands/lint-copyright.star reads module globals, calls sibling module
    functions, and calls provider predeclareds (file.read_text, regex.match) -- every one undefined in the
    synthesized module. The archival wrap would deliver a feature that works only for a reducer using nothing but
    its own parameters and Universe builtins.

    It imports side effects into a read-only surface. buildCandidate runs before the catalog is consulted
    (resource.go:178-189), and newFromSource unconditionally does MkdirAll(0700) + WriteFile(0600) of a
    pack into <root>/.devlore/function/resource/sha256/<xx>/<hex> on every call -- per call, not per distinct
    function, because the catalog dedupes only the entry (resource_catalog.go:304-312). It calls
    runtimeEnvironment.Root() with no HasRoot guard, and Root() panics via assert.Failf for a
    root-less session (runtime_environment.go:341-346). It re-reads and re-parses the user's .star file
    unsandboxed on every call (synthesize.go:174-180). Under star the root is os.Getwd()
    (cmd/star/extension/application.go:71-89), so a lint pass would litter the working tree.

    3. The answer is a live bridge, and the layering permits it

    starlarkbridge.NewInvoker() is explicitly environment-free (invoker.go:39-50): no root, no disk, no
    catalog, and the callable keeps its own module, so globals, sibling functions and predeclareds all resolve.

    Layering verified by grep, not assumed: starlarkbridge imports pkg/op (go_receiver.go:16) and imports no
    provider; pkg/op never imports starlarkbridge (only doc-comment mentions at graph_executor.go:360 and
    runtime_environment.go:45). So an init() in starlarkbridge registering into op is cycle-free, in the
    shape op.RegisterPlanPathNormalizer already uses (pkg/op/plan_path.go:18-74).

    Placement: op.Convert, immediately before return nil, explainRefusal(value, target) (convert.go:137),
    gated on target.Kind() == reflect.Func. It must sit after convertDirect (convert.go:84) so an any
    target short-circuits at convert.go:209 -- that is what keeps the two lambda desugar sites that type-assert
    the raw *starlark.Function working (plan/provider.go:683-690, flow/planners.go:737-745). It must read
    value, not the elem deref at convert.go:88-91 (a *starlark.Function derefs to a struct). It must sit
    after step 5 so a real function.Resource still routes through its own ConvertTo.

    Nothing changes in plan mode: bindAuthoredValue wraps to a function.Resource before Convert ever runs
    (planner.go:436-447), so the new step never sees a bare *starlark.Function there.

    4. Two things that must land in the same commit

    A pre-existing panic becomes reachable. funcReturn does
    out[0] = reflect.ValueOf(result).Convert(target.Out(0)) with no nil guard (resource.go:1018-1031), and
    converter.go:424-425 maps starlark.NoneType to Go nil. So a reducer that returns None -- or simply falls
    off the end, which Starlark allows -- panics inside reflect rather than erroring. Today Convert refuses
    before the bridge exists, so author code cannot reach it. This change makes it reachable on every call.

    A recorded ruling must be amended, not contradicted silently.
    docs/plans/extract-starlark-from-op/phase-8/steps/25-function-values-bridge.md:20 reads: "(b) dispatch-time
    landed as a SourceConverter opt-in, not a reflect.Func branch inside Convert."
    That rejection was aimed
    at a step with environment-dependent side effects; a pure live bridge has none. The ruling still has to be
    amended in the same commit that reopens it.

    Honest caveat on this research

    It was framed as "is the wrap sufficient" -- a minimality framing that was ruled against mid-flight. Its
    substance rejected the cheap fix anyway, on correctness, and chose the more invasive bridge. So the conclusion
    survives the framing, but this is a mechanism answer, not a comparison of designs. A four-design judge panel
    is scripted and cached if the design space is worth opening.

  3. David-Noble-at-work commented on Nov 9, 2026

    @David-Noble-at-work
    ContributorAuthor

    star github triage sweep added this issue to Triage: devlore, for the rule it breaks:

    • no-evidence: no Evidence of completion section
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions