stackdump

Things I learned while programming as a Petri-net maximalist.

Pflow’s workflow implementation simplifies and extends WF-net ideas for practical, real-world systems by:

  1. Adding retry and reentry mechanisms (allow_reentry).

  2. Restricting state behaviors to enforce runtime constraints.

  3. Focusing on execution rather than pre-runtime verification.

WF-nets remain a formal and abstract framework for analyzing workflows, often requiring specialized tooling and theoretical grounding. Pflow’s workflow model aligns more with runtime task automation and system engineering.

I recently attended an Austin hackathon oriented around the latest open source models from Meta. https://lu.ma/atx-llama-hackathon.

As the main sponsor, representatives from Meta are spreading the word about their impact grant program. https://www.llama.com/llama-impact-grants/

I got to work with some great tools from these additional sponsors:

Pflow-prompt

During this hackathon, I decided to try to test the ability for for Llama to generate petri-nets using the pflow.xyz notation.

I’ve been interested in trying to use LLMs to convert code into equivalent petri-net models. So, I started with a program written in a state-machine style in BASH.

I then provided it as user input, alongside a system prompt:

Output models:

Remarks

I’m pretty impressed with how well OpenAI 4o performed. The LLM correctly intuited that we’d like to use the state and action names as labels.

It also seemed to do a good job laying out the objects, and using the playground feature, I was even able to prompt another time to ask it to “add more space between the elements” – with consistent results.

Most of the other submissions made use of natural language translation and auto-classification.

Upon reflection: I could have applied the RAG approach using tools provided by Datastax, or built a tool using lang-graph, or even tried model refinement to get the results I wanted from Llama.

In the end, because OpenAI 4o worked with a single prompt I didn’t see any benefit to try to use Llama.

While developing this experiment I used the API https://platform.openai.com/ and only spent $.06 !!

Conclusion:

For now, I’ll be using 4o as I add LLM support to pflow.xyz.

Going forward, my sense is that various refinement approaches will become less relevant as better LLMs are developed, and for now the cost seems to be right for this application.

1. PetriNet

  • General Behavior: Petri nets allow the most general and flexible state transitions, supporting multiple states being active at once and various roles or conditions for enabling transitions.
  • Fire Method: petri_net_fire
    • Transitions update states based on their delta values.
    • Guards are applied to inhibit transitions if conditions are not met.
    • The result includes flags for overflow, underflow, and whether the transition was inhibited.
    • Supports full vector addition for state changes, with capacity checks.
  • Key Features:
    • Most complex and capable model.
    • Can handle arbitrary guard conditions and multiple active states.

2. Elementary

  • General Behavior: Simplifies the Petri net model, restricting the number of active states post-transition to one. This ensures clear, single-state progression.
  • Fire Method: elementary_fire
    • Works similarly to petri_net_fire, but includes an additional check to ensure only one state is active (output_state_count == 1).
    • Transitions are inhibited if multiple states are active after firing.
  • Key Features:
    • Simplifies state behavior by enforcing single-state transitions.
    • Suitable for workflows where transitions must always result in a single active state.

3. Workflow

  • General Behavior: A further simplification of the Elementary model, explicitly designed for workflows with retry and reentry behavior. Allows more leniency in retrying failed transitions while enforcing constraints on state updates.
  • Fire Method: workflow_fire
    • States are constrained to values 0, 1, or 2:
    • 0 or -1: Inactive states or retryable errors.
    • 1: Active state.
    • 2: Overflow; mapped to 1 for retry or inhibited transitions.
    • Enforces single active state but introduces retry behavior.
    • Allows transitions with specific conditions (e.g., allow_reentry).
  • Key Features:
    • Designed for task flows or processes with explicit reentry behavior.
    • Introduces stricter constraints but enables retry loops for overflow states.

Comparison


Practical Applications:

  1. PetriNet: Use for complex, concurrent systems where multiple states must interact or coexist.

  2. Elementary: Apply to simpler decision trees or systems that require deterministic, single-state outputs.

  3. Workflow: Ideal for workflows or task management systems where retry and fail-safe mechanisms are essential.

This framework allows flexible modeling based on system requirements, enabling efficient and accurate representation of different operational paradigms.

Review the Rust code on used to compare these algorithms on github.

Orthographic & Isometric Drawing - MR. ELSIE - TECHNOLOGICAL EDUCATION

In the realm of software design, visualizing complex systems is paramount. Drawing inspiration from isometric projection—a drafting technique that represents three-dimensional objects in two dimensions—we can adopt a similar approach using Petri nets. This method offers a comprehensive perspective on system workflows and resources.

Isometric Projection: A Brief Overview

Isometric projection allows for the depiction of 3D objects on a 2D plane without distortion, maintaining equal scale along three axes. This technique provides a clear and detailed view of intricate structures, facilitating better understanding and analysis.

Petri Nets: Modeling System Dynamics

Petri nets are mathematical representations used to model distributed systems. They consist of places (depicting states), transitions (representing events), and arcs (indicating the flow between places and transitions). This framework effectively captures the dynamic behavior of systems, including concurrency and resource sharing.

Integrating Isometric Principles with Petri Nets

By applying the concept of isometric projection to Petri nets, we can create layered models that offer multiple perspectives of a system:

  1. Primary Net: Illustrating the Overall Workflow

The primary Petri net serves as a high-level map of the system's main processes. It outlines the general flow, highlighting key transitions and states. This top-level view provides a clear understanding of the system's core functionality.

  1. Sub-Nets: Detailing Resources and Sub-Workflows

Sub-nets delve into specific components, such as resources or subsidiary workflows. Each sub-net focuses on a particular aspect, offering detailed insights into its operations and interactions. This modular approach simplifies complex systems by breaking them down into manageable sections.

  1. Composite View: Achieving a Comprehensive Projection

Combining the primary net with its associated sub-nets results in a holistic representation of the system. This integrated model mirrors the clarity of an isometric projection, allowing for simultaneous examination of the system's overall structure and its detailed components.

Advantages of This Approach

  • Enhanced Clarity: Layered modeling clarifies complex systems, making them easier to understand and analyze.
  • Modularity: Sub-nets enable focused examination of individual components, facilitating targeted development and troubleshooting.
  • Scalability: This method accommodates system growth, allowing for the addition of new sub-nets as the system evolves.

Conclusion

Embracing the principles of isometric projection through the use of Petri nets offers a structured and comprehensive approach to software design. This technique not only enhances visualization but also improves the management and scalability of complex systems.

To see how this this actually done start with: 3 Petri-Net Data Types

This blog post is NOT about LLMs!! The term Model is barely mentioned now-a-days without a prefix — as “Large Language Models” have reshaped the technical landscape.

A model is an abstract representation of a process that is composed of both behaviors (actions) and attributes (data). A good model allows for a system to be more predictable and easier to understand. A great model can also reduce the code complexity of a program.

Building Functional Models

Functional programming philosophy tells us that any problem can be solved via a reductionist approach: the developer decomposes a problem into functions, and then re-composes those functions into a solution.

This same paradigm is can be formally applied using petri-net models. First, we model the problem to be solved as a series of events. Then, by linking actions with input and output states, we compose these events into a full solution.

Net Analysis

Petri-nets are a formal analysis tool providing a formal foundation at design time, but we can also use them to make assertions about our program at runtime.

One useful attribute for analysis is reachability:

Given an input state, can the petri-net state machine be transformed into a target state?

Another testable property is boundedness:

Does this net model a closed system? Can a given place ever hold more than N tokens? Does the system ever create or destroy tokens?

The last property we hilight is liveness:

Can the network reach a state where no transformations are possible? under what conditions does the network reach this halting state?

Many of these properties can be analyzed through simulation. The petri-net itself is an executable schema. Pflow leverages this ability to interact with a model as a way to let users perform these checks simply by running model in a browser.

Conclusion

Building models into our code can improve design and the execution. Small models are comprehensible a user and developer alike. For a software developer, using a state machine for problem solving applies rigor at both design-time and program runtime. As a user, models can inform and educate about the state of a running process while interacting with a program. Check out the resources below how to use models in your code:

Visit https://pflow.xyz/docs-petri-net-101 to learn more about petri-nets, or try to compose one yourself using the editor https://pflow.xyz/editor.

Pflow.xyz is an SDK for constructing petri-net smart contracts.

This article explores some features of the PflowDSL – which is an internal DSL to build models embedded in solidity code.

This is an excerpt from a demo model deployed to sepolia-optimism testnet. The above model contains every term that the language allows for, here’s a translation to petri-net terminology.

  • cell()[place] declares a memory location in the ‘state’ of the model
  • func()[transition] declares a transformation that mutates state
  • arrow()[arc]connectes cell() –> func() or func() –> cell
  • guard()[inhibitor arc] an arrow used as a ‘if/unless’ precondition

Some additional attributes of the language:

Declarative Style: Using the DSL is essentially describing the structure of the Petri net (places, transitions, arcs) rather than providing step-by-step instructions on how to build it.

  • Functional Composition: The DSL uses functions like cell, func, arrow, and guard to define individual components and then connect them to form the complete net.
  • Data-Centric: The core data structures are places and transitions, and the functions operate on and modify these structures.

Syntax:

  • Function Calls as Building Blocks: The syntax of function calls in the DSL (cell(...), func(...)) visually resembles Lisp's s-expression syntax, where everything is enclosed in parentheses and the first element is typically the function name.
  • Minimal Syntax: The DSL keeps the syntax quite minimal, focusing on the essential elements needed to define the Petri net.

Altogether, the Pflow SDK provides a way to enrich the syntax of your contract using another derived App-specific language.

Notice that in animation below -

The labels of the model can be used to visualize the state of the contract —also including a red/green coloring to indicate the ‘fireable-ness’ of the transition.

In conclusion

Pflow.xyz, with its internal PflowDSL, offers a novel and expressive approach to building Petri-net smart contracts. By enabling a declarative, functional, and data-centric construction of complex state machines, it enhances the clarity and maintainability of your Solidity code.

Learn more about how to make these models! Explore the solidity API: in the pflow.xyz docs. Or, view source code for the demo on sepolia-optimism testnet block explorer.

We recently participated in Base’s on-chain Summer. full code on github: https://github.com/stackdump/on-chain-summer-2024

How it Started

Our intention for this hackathon was to build out an on-chain crafting game.

We didn’t develop it enough to submit for judging, but we did learn a few things about our design.

  1. Models have a limit of about 100 objects (places,transitions,arcs) for a single contract deployment.

  2. Nodes-as-a-service do not always have a suitable free tier.

  3. Our block-synching approach seemed to scale well enough on testnet.

  4. The onchain model structure can be improved.

Finding Limits

We discovered that models are limited to about 100 total objects including the types: Places, Transitions, Arcs.

Arcs (0.0279 KiB) are about 2-3x as ‘expensive’ in code as a Place (0.0956 KiB) or Transition (0.0872 KiB).

The Initial design we attempted was about 10 Kib (~48 Arc objects) over the limit for a smart contract max initcode size.

Block Synching

Tested free tier usage from these providers.

  • QuickNode – reliable nodes, limited to a single node per project
  • BlastApi – crypto native, supports mainnet/testnet for each project.

QuickNode seemed to provide the most credits in a free tier.

BlastAPI seems to be a crypto native approach to hosted nodes, requiring only a wallet to try it out.

In both cases our testnet api seemed to keep up during normal synching.

Block Synching

Our design utilized a postgres database image from supabase: https://github.com/supabase/postgres

Supabase/postgres comes pre-baked with pgnet and pgcron support.

These two features allows for the creation of a self-synching postgres db, where a cron runs pl/sql functions to import block data every 1 min.

We tested using a local image, and the free tier db-as-a-service from supabase.com. In both tests result success was limited by the API we were using, and the DB instance seemed to perform well enough during our week of testing.

Model Improvements

Upon realizing our space limits += 100 objects, we looked to code that could be removed, generally there was some overhead we could lower ~ 2KiB but the contract size growth was mostly related to the complexity of the design.

In the future we intend to investigate some of the multi-contract & library deployment patterns to attempt to create larger model designs.

Conclusion

Though we learned a lot, ultimately we felt that our project wasn’t developed enough to present for judging.

You can see the crafting system design we created below.

You can out the model here: https://pflow.dev/p/zb2rhnuKVVerJd9GA2H4VghgnVUxjUTajKhuaC7XJXjaVUzna/

I have been preparing to launch a Dapp pflow.xyz on Optimism Mainnet. This felt like an appropriate time to look back at at that first moment of inspiration.

I first conceived of this project 10 years ago (while taking a shower) – and immediately bought a domain name: bitwrap.io.

My original inspiration was bitcoin’s OP_RETURN though I was mining Litecoin at that time due to hash difficulty.

Some time before that I attended a meetup in La Jolla, Ca where Vitalik gave a remote presentation about Ethereum’s upcoming DAO – I was honored to get to ask him an embarrassingly simple question like “How do you make a DAO” – [I think we are collectively still working on that question].

I believe we are now seeing a slow motion revolution happen. A global inversion of the control of data as a public good. Rather than private companies having sole control of data flows, users can now opt-in to leaderless platforms that have incentivized reasons to exist, and to continue existing.

This opens a new space for ideas to intermix, and evolve in a way that could not happen before this web3 commons came into existence.

Even now 10 years later I’m continually inspired to build tools that hasten this inversion, and I can’t wait to see what we build next.

Information wants to flow & “Information wants to be free.” This is why I’m building pflow.xyz

(Verse 1) Back in '39, a young genius did find, A way to chart processes, leaving none behind. Carl Petri, just thirteen, with a vision so keen, Mapped out the flow of systems, a mathematical dream.

(Chorus) Dancing through the nets, where tokens freely roam, In places and transitions, they find their way home. A bipartite graph, so elegantly composed, Petri nets, where complexity is neatly enclosed.

(Verse 2) From chemistry to computing, his idea took flight, A universal language, turning complexity to light. Arcs and places, transitions in between, A ballet of tokens, in a machine's serene dream.

(Bridge) Non-deterministic, yet so precise, Modeling concurrency, cutting through like a knife. Enabled transitions, a firing sequence so bright, Petri nets illuminate, the theoretical night.

(Verse 3) With every token's journey, a story unfolds, A dance of possibilities, as the future holds. From discrete events to continuous flow, Petri nets capture dynamics, as they go.

(Chorus) Dancing through the nets, where tokens freely roam, In places and transitions, they find their way home. A graphical notation, for processes so wide, Petri nets, our faithful guide, with Carl by our side.

(Outro) So here's to Carl Petri, and his brilliant insight, A mathematical model, to bring complexity to light. Through places and transitions, our systems we compose, With Petri nets, the path of clarity brightly glows.

1. Workflow Model

Definition: The Workflow model represents the structured sequence of processes or activities aimed at accomplishing a specific task or goal. It defines the flow of tasks, decisions, and information in organizational processes or systems.

Core Components:

  • Activities: Discrete tasks or operations within the workflow.
  • Transitions: The movement or progression from one activity to another.
  • Actors: Entities (either human or automated) responsible for performing the activities.
  • Data: Information that flows through the workflow, being input, manipulated, or output by activities.
  • Triggers: Events or conditions that initiate or influence the flow of activities.

Usage Context: Used in business process management, software development, and automation systems to streamline and optimize processes.

2. Petri-Net Model

Definition: A Petri-net is a mathematical modeling language used for the description and analysis of systems characterized by concurrency, parallelism, synchronization, and nondeterminism. It extends beyond simple workflow models by providing a graphical and mathematical representation of distributed systems.

Core Components:

  • Places: Represent conditions or states of the system.
  • Transitions: Symbolize events that can change the state of the system.
  • Tokens: Denote the presence or absence of certain conditions. The distribution of tokens across places represents the current state of the system.
  • Arcs: Connect places to transitions (and vice versa), dictating the flow of tokens and thus the allowable transitions based on the current state.

Usage Context: Widely used in the fields of computer science and systems engineering for modeling complex systems, analyzing performance, and verifying system properties.

3. Elementary Nets (EN) Model

Definition: Elementary Nets (EN) are a simplified version of Petri-nets focused on the fundamental aspects of system behavior, particularly the notions of causality and conflict without considering complex data or hierarchical structures.

Core Components:

  • Conditions: Similar to places in Petri-nets, conditions represent the state of the system but are more binary in nature, indicating whether a condition is true or false.
  • Events: Analogous to transitions, events denote changes between conditions. An event occurs if and only if all its preconditions are true, and its occurrence results in the postconditions becoming true.
  • Arcs: Define the relationship between conditions and events, indicating which conditions must be true for an event to occur and which conditions become true after an event occurs.

Usage Context: ENs are used for modeling and analyzing simple systems or processes where the focus is on the presence or absence of conditions and the basic causality relationships between events. They serve as a foundational concept for understanding more complex Petri-net variants and are useful in educational settings or initial system design phases.

Each of these models serves different but complementary roles in analyzing and designing systems, from simple workflows to complex systems characterized by concurrent and parallel processes.