viv icon indicating copy to clipboard operation
viv copied to clipboard

Runtime error if the last instruction in a plan phase is a loop

Open trillioneyes opened this issue 6 months ago • 1 comments

Component (compiler, runtime, a specific plugin, other): Runtime

Component version(s): Commit 8ff538e67656d70ac728f5d24e1308f553001bda, which I believe is runtime 0.10.2.

What happened: Upon running the minimal reproduction case, the following error comes out of the viv runtime:

TypeError: Cannot read properties of undefined (reading 'type')
    at async (/home/alyssa/petals/node_modules/@siftystudio/viv-runtime/src/planner/planner.ts:316:32)
    at async (/home/alyssa/petals/node_modules/@siftystudio/viv-runtime/src/planner/planner.ts:250:15)
    at async async (/home/alyssa/petals/node_modules/@siftystudio/viv-runtime/src/planner/planner.ts:187:33)
    at async async (/home/alyssa/petals/node_modules/@siftystudio/viv-runtime/src/planner/planner.ts:105:27)
    at async async (/home/alyssa/petals/node_modules/@siftystudio/viv-runtime/src/planner/planner.ts:59:47)
    at async async (/home/alyssa/petals/node_modules/@siftystudio/viv-runtime/src/api/planning.ts:123:5)
    at async main (/home/alyssa/petals/src/main.ts:174:5)
    at async <anonymous> (/home/alyssa/petals/src/main.ts:191:3)

Having squinted at the compiled content bundle for a bit, it looks like this happens because in the context of a plan phase, a loop gets compiled to something like this:

{
    ...,
    tape: [
        {type: "loopInit", ...},
        {type: "loopNext", exitTarget: 4}, // exitTarget points to the instruction AFTER the jump
        {type: "...", ...}, // body of the loop goes here. May be multiple statements, in which case the exitTarget will be different.
        {type: "jump", target: 1}, // jump back to the loopNext instruction
        // loopNext exitTarget points here -- but since the loop is the last statement in the phase, it's null!
    ],
    ...
}

If the current plan phase has an instruction following the loop, this is the desired behavior. But if the loop was the final statement in that phase, we'll set the instruction pointer to a nonexistent instruction instead of advancing to the next phase, leading to the above TypeError when we look up the type property of the next instruction when we evaluate it. What you expected: If the final statement of a plan phase is a loop, after exiting the loop execution should continue to the next plan phase (or the plan should succeed if none exists). Also, I would expect this error to be a VivError rather than a raw TypeError.

Steps to reproduce: Start from the hello-viv-ts example. Replace src/content/source.viv with this:

action debug:
    gloss: "Debug @person"
    roles:
        @person:
            as: initiator

plan debug-plan:
    roles:
        @people*:
            as: character
            n: 3
    phases:
        >phase-one:
            loop @people* as _@person:
                queue action debug:
                    with:
                        @person: _@person
            end

and add the following lines to src/main.ts:

 async function main(): Promise<void> {
     // Set things up
     initializeVivRuntime({ contentBundle: CONTENT_BUNDLE, adapter: ADAPTER });
     createWorld();
+    queuePlan({planName: "debug-plan"})
     // Simulate three timesteps, selecting an action for each character on each one
     for (let timestep = 0; timestep < 3; timestep++) {
+        await tickPlanner()
         for (const characterID of STATE.characters) {
             await selectAction({ initiatorID: characterID });
         }
         STATE.timestamp += 10;
     }
     // Print what happened
     console.log("\n=== Chronicle ===\n");
     for (const actionID of STATE.actions) {
         const action = STATE.entities[actionID] as ActionView;
         const summary = action.report ?? action.gloss ?? "(no summary)";
         console.log(`  [T=${action.timestamp}] ${summary}`);
     }
     console.log();
 }

Then compile the viv content bundle and run npm start.

Workaround: Add a dummy statement to the end of any plan phase that ends in a loop.

trillioneyes avatar May 11 '26 15:05 trillioneyes

@trillioneyes Thank you for reporting this bug!

Your breakdown was spot on. Reaching the end of a phase tape should trigger a phase advance, but this wasn't working in cases where the end of the tape is targeted via a jump. This affected phase-final loops, as you discovered, and also phase-final conditionals.

The bug is fixed in runtime v0.10.3: npm install @siftystudio/viv-runtime@latest. And if the program counter does reach a truly invalid position, a structured VivExecutionError will now be thrown in lieu of a raw TypeError like you had received.

Investigation of this problem also revealed a similar issue in the compiler, where jumps out of conditionals skipped the first instruction following the conditional. This bug is fixed too, in compiler v0.12.2: pip install --upgrade viv-compiler.

Thanks again, and happy planning!

james-owen-ryan avatar May 15 '26 07:05 james-owen-ryan