Skip to content

Example 3 Add Context and Policy

Fernando Koch edited this page Mar 30, 2026 · 3 revisions

Example 3: Add Context And Policy

Goal

Understand how GraphK controls execution with scoped context and validation rules.

Scenario

The pipeline is no longer just a straight sequence. Now execution should depend on where a node is running and whether the current state satisfies the expected rules.

Example

import graphk


allow_entry = graphk.Policy(task="go", **{"@Node/stage": "work"})

pipeline = graphk.SequencePipe(
    nodes=[
        graphk.demo.IncrementNode(
            "Prepare",
            increment=2,
            target_key="counter",
            response=True,
            context=graphk.Context(stage="work"),
            entry_policy=allow_entry,
            exit_policy=graphk.Policy(counter=">=2"),
        )
    ]
)

program = graphk.Program(
    {"policy": pipeline},
    context=graphk.Context(mode="strict"),
)

emitter = graphk.Emitter(program)
emitter.request("policy", graphk.Session(task="go", counter=0))

print(emitter.response())

What Happens?

  • program context introduces shared scoped execution values
  • policy checks whether execution is allowed
  • the node only runs when the rule set matches the active state

Why This Example Matters

This is where GraphK starts becoming a governed runtime rather than a plain ordered sequence.

Run The Full Examples

Clone this wiki locally