# M2 Animation Resource Finalizer

## Metadata

| Field | Value |
|---|---|
| Status | Implemented extraction |
| Target/work package | M03 / `M03-RND-M2-ANIMATION-RESOURCE-FINALIZER-001` |
| Owners | Cached animated Resource polling, terminal load and prototype outcome |
| Last verified | Worktree `work/sindo-main-codex/m03-m2-animation-resource-finalizer`, 2026-07-18 |
| Profiles/capabilities | Existing optional cached-GLB animated M2 path |

## Purpose

Drain cached animated M2 ResourceLoader work without keeping terminal I/O and
prototype outcome logic in `StreamingWorldLoader`. The service polls pending
requests, prepares a detached scene candidate and completes material repair,
validation, cache adoption or static-only fallback.

## Non-goals

- Select cached GLB paths, apply allow/deny policy or admit threaded requests.
- Select/build native animated M2 prototypes.
- Look up the static material prototype used for repair.
- Own render permits, build jobs, playback, instances or SceneTree roots.
- Change ResourceLoader ordering, cache formats, profiles or visible output.

## Context and boundaries

```mermaid
flowchart LR
    Observer[M2CachedAnimationResourceObserver] --> Pipeline[M2AnimationLoadPipelineState]
    Loader[StreamingWorldLoader] --> Finalizer[M2AnimationResourceFinalizer]
    Pipeline --> Finalizer
    ResourceLoader --> Finalizer
    Finalizer --> SceneFinalizer[M2AnimatedSceneFinalizer]
    Finalizer --> Cache[M2PrototypeCacheState]
    Loader --> Material[Material prototype lookup]
    Material --> Finalizer
```

The two-phase API preserves the historical ordering: a loaded Resource must
instantiate a candidate before the loader performs material-prototype lookup.

## Public API

| Symbol | Kind | Purpose | Failure behavior |
|---|---|---|---|
| `poll_terminal_requests(pipeline, cache)` | I/O command | Move LOADED/FAILED requests to completion FIFO | Invalid composition returns zero |
| `prepare_next_candidate(pipeline, cache)` | I/O command/query | Pop one record, load Resource and instantiate candidate | Skip/failed/invalid outcome returns empty Dictionary |
| `finalize_prepared_candidate(preparation, material_source, cache, debug)` | Command/query | Repair, validate, adopt/log or mark static-only | Invalid/finalization failure returns null |
| `load_threaded_get_status(path)` | I/O adapter | Production status query with injectable test seam | Returns ResourceLoader status |
| `load_threaded_get(path)` | I/O adapter | Production terminal Resource retrieval with injectable test seam | May return null |

## Inputs and outputs

| Direction | Data | Producer | Consumer | Ownership/lifetime |
|---|---|---|---|---|
| Input | Pending/finalize records | Animation pipeline | Finalizer | Pipeline-owned copied Dictionaries |
| Input | ResourceLoader status/Resource | Godot ResourceLoader | Finalizer | Resource reference for one operation |
| Input | Material source root | Loader lookup | Scene finalizer | Borrowed exact Node3D |
| Input | Prototype/static-only state | Prototype cache | Finalizer | Borrowed service; loader session |
| Output | Prepared candidate Dictionary | Finalizer | Loader/finalizer completion | Caller-owned, immediate operation |
| Output | Canonical animated prototype | Prototype cache | Loader build path | Borrowed exact Node3D |
| Output | Static-only outcome | Finalizer | Prototype cache | Copied path; loader session |
| Output | Success diagnostic | Finalizer | Runtime log | Debug-gated one-line record |

## Data flow

```mermaid
flowchart TD
    Poll[Poll pending records in insertion order] --> Path{Resource path empty?}
    Path -->|yes| Discard[Discard and mark static-only]
    Path -->|no| Status{LOADED or FAILED?}
    Status -->|no| Pending[Keep pending]
    Status -->|yes| Complete[Append completion FIFO]
    Complete --> Permit[Loader consumes one finalize permit]
    Permit --> Pop[Pop oldest terminal record]
    Pop --> Existing{Empty/cached/static-only?}
    Existing -->|yes| Skip[Finish permit operation]
    Existing -->|no| Loaded{Status LOADED?}
    Loaded -->|no| Mark[Mark static-only]
    Loaded -->|yes| Get[Get terminal Resource]
    Get --> Instantiate[Instantiate detached candidate]
    Instantiate --> Valid{Candidate exists?}
    Valid -->|no| Mark
    Valid -->|yes| Material[Loader resolves material source]
    Material --> Repair[Repair and validate]
    Repair --> Prototype{Prototype accepted?}
    Prototype -->|no| Mark
    Prototype -->|yes| Adopt[Adopt and optionally log]
```

## Lifecycle/state

```mermaid
stateDiagram-v2
    [*] --> Polling
    Polling --> Pending: nonterminal status
    Polling --> TerminalQueued: LOADED or FAILED
    Polling --> StaticOnly: empty Resource path
    TerminalQueued --> Skipped: cached/static/invalid record
    TerminalQueued --> StaticOnly: failed load or invalid candidate
    TerminalQueued --> Prepared: detached candidate
    Prepared --> Adopted: repair/finalize succeeds
    Prepared --> StaticOnly: validation fails
    Pending --> [*]
    Skipped --> [*]
    StaticOnly --> [*]
    Adopted --> [*]
```

## Main sequence

```mermaid
sequenceDiagram
    participant L as StreamingWorldLoader
    participant F as AnimationResourceFinalizer
    participant P as AnimationLoadPipelineState
    participant R as ResourceLoader
    participant S as AnimatedSceneFinalizer
    participant C as PrototypeCacheState
    L->>F: poll_terminal_requests(P, C)
    F->>R: load_threaded_get_status(path)
    F->>P: complete terminal request
    L->>L: consume M2_ANIMATION_FINALIZE permit
    L->>F: prepare_next_candidate(P, C)
    F->>P: pop oldest finalize record
    F->>R: load_threaded_get(path)
    F->>S: instantiate_candidate(Resource)
    alt candidate available
        F-->>L: normalized/path/candidate
        L->>L: resolve material prototype
        L->>F: finalize_prepared_candidate(...)
        F->>S: repair_materials + finalize_candidate
        F->>C: adopt prototype or mark static-only
    else rejected
        F->>C: mark static-only
    end
```

## Dependency diagram

```mermaid
flowchart TB
    Finalizer[M2AnimationResourceFinalizer] --> ResourceLoader
    Finalizer --> Pipeline[M2AnimationLoadPipelineState]
    Finalizer --> SceneFinalizer[M2AnimatedSceneFinalizer]
    Finalizer --> Cache[M2PrototypeCacheState]
    Loader[StreamingWorldLoader] --> Finalizer
    Loader --> Scheduler[RenderBudgetScheduler]
    Loader --> MaterialLookup[Material prototype lookup]
    Finalizer -. no dependency .-> Scheduler
    Finalizer -. no dependency .-> BuildQueue[M2BuildQueue]
    Finalizer -. no dependency .-> Playback[M2AnimationPlaybackController]
```

## Ownership, threading and resources

- All methods run synchronously on the renderer main thread.
- Pipeline owns pending and completion records; one loader permit pops one record.
- The prepared Dictionary temporarily owns the detached candidate reference. The
  loader must call completion synchronously after material lookup.
- Existing scene finalizer frees rejected candidate roots. Prototype cache owns
  accepted detached prototypes until final shutdown.
- Service retains only scene-finalizer and optional test-adapter references. The
  production ResourceLoader path creates no self-reference or retained Resource.
- Loader retains scheduler permits, material lookup and all instance/SceneTree work.

## Errors, cancellation and recovery

| Failure/state | Behavior | Recovery |
|---|---|---|
| Missing service dependency | Return zero/empty/null | Correct renderer composition |
| Empty Resource path | Discard pending request and mark static-only | Repair cache and start new session |
| Nonterminal status | Keep request pending | Poll next tick |
| FAILED terminal status | Pop one record and mark static-only | Repair cache and start new session |
| Existing cached/static state | Pop and skip without terminal Resource get | None |
| Null/unsupported Resource | Mark static-only | Repair imported cache |
| Candidate validation failure | Scene finalizer frees candidate; mark static-only | Repair animation/cache |
| Tile cancellation | No direct transition; shared cache work continues | Loader queue remains authoritative |
| Shutdown | Loader drains ResourceLoader before pipeline/cache clear | New loader starts empty |

## Configuration and capabilities

The module adds no setting. Existing cached-animation allow/deny policy,
`m2_animation_finalize_ops_per_tick`, debug flag and scheduler lane remain exact.

## Persistence, cache and migration

No persistence, schema or cache path changes are introduced. Existing `.glb`
imports and `pivot_prefix_v1` eligibility remain owned by the cached observer.

## Diagnostics and observability

Successful debug-enabled adoption emits the unchanged `M2_ANIM_CACHE` record
with normalized path, Resource cache path and AnimationPlayer count. Pipeline
work metrics remain pending plus completion FIFO size.

## Verification

- Dedicated verifier covers pending/loaded/failed polling order, empty path,
  completion FIFO, cached/static skips, terminal Resource get, candidate identity,
  material repair arguments, adoption, rejection, source ownership and timing.
- Pipeline, scene-finalizer, prototype-cache, cached-observer, shutdown, facade,
  internal-access and baseline regressions protect adjacent behavior.
- Fidelity evidence is exact lifecycle/I/O extraction only; no private asset,
  original-client animation, visual, leak-pressure or p95/p99 claim is made.

## Extension points

Material-prototype lookup may later become a dedicated resource observer, which
would allow the entire two-phase operation to compose outside the loader. Static
Mesh Resource finalization remains separate to avoid premature generalization.

## Capability status

| Capability | Status | Evidence | Gap/next step |
|---|---|---|---|
| Animated request terminal polling | Implemented extraction | Status/order/source verifier | Asset-backed long traversal pending |
| Animated candidate finalization/outcome | Implemented extraction | Identity/repair/adoption verifier | Private visual/leak/p95/p99 pending |
| Material prototype lookup | Loader-owned | Existing renderer regressions | Dedicated observer optional |

## Known gaps and risks

- Terminal Resource get, instantiation and repair remain synchronous main-thread work.
- Prepared candidate ownership relies on immediate completion by the loader adapter.
- Private asset traversal, descriptor pressure, leak and p95/p99 evidence is absent.

## Source map

| Path | Responsibility |
|---|---|
| `src/render/m2/m2_animation_resource_finalizer.gd` | Poll/load/prepare/finalize/cache/log service |
| `src/render/m2/m2_animation_load_pipeline_state.gd` | Pending and completion FIFO ownership |
| `src/render/m2/m2_animated_scene_finalizer.gd` | Candidate instantiation/repair/validation/rejection cleanup |
| `src/render/m2/m2_prototype_cache_state.gd` | Accepted prototype/static-only ownership |
| `src/scenes/streaming/streaming_world_loader.gd` | Permits, material lookup and synchronous composition |
| `src/tools/verify_m2_animation_resource_finalizer.gd` | Polling/finalization/boundary/timing regression |

## Related decisions and references

- [`m2-animation-load-pipeline-state.md`](m2-animation-load-pipeline-state.md)
- [`m2-animated-scene-finalizer.md`](m2-animated-scene-finalizer.md)
- [`m2-cached-animation-resource-observer.md`](m2-cached-animation-resource-observer.md)
- [`m2-prototype-cache-state.md`](m2-prototype-cache-state.md)
- [`world-renderer.md`](world-renderer.md)
- [`../../RENDER.md`](../../RENDER.md)
- [`../../targets/roadmap/02-rendering-and-graphics.md`](../../targets/roadmap/02-rendering-and-graphics.md)
