Skip to content

Keep Records in Memory

InMemoryEgress keeps a run's records in the Python program that runs the model, and returns them as pyarrow tables after the run. A program can then use the records in the same process, for example to train or test a model, with no file and no service. This page runs a shop for two minutes, reads its events and telemetry as tables, and converts the events to pandas.


Before You Start

  • Egress describes the sink, and Records and Telemetry the fields of a record.
  • Install the extra: pip install "desflow[parquet]". The sink needs pyarrow, from the same extra as the Parquet sink.
  • The conversion to pandas needs pandas, which desflow does not install: pip install pandas.

Steps

Add the Sink

The sink is added in Python in every form. The program then runs the model and reads the sink after the run:

The blueprint names no sink:

docs/snippets/yaml/keep_records_in_memory.yaml
# The Keep Records in Memory guide: one packer, orders about every 2 seconds, and
# readings every 30 seconds. It names no sink, because a blueprint cannot name
# InMemoryEgress: keep_records_in_memory_yaml.py loads it and adds the sink.
# Run it with: python keep_records_in_memory_yaml.py
simulation: {sim_id: Shop, factor: 0, random_seed: 42}

resources:
  packers: {current_cap: 1, max_cap: 1}

services:
  packing: {dist: constant, value: 1.5}

arrivals:
  orders: {dist: exponential, rate: 0.5, spawn: pack_order}

tasks:
  pack_order:
    service: packing
    resource: packers
    # The finished event is the order record
    payload:
      order_id: {gen: sequence}
      amount: 19.99

# Readings every 30 seconds, as telemetry
stats: {level: minimal, interval: 30}

run: {until: 120}

A blueprint cannot name InMemoryEgress, because desflow run has no program to hand the tables to: an entry type: InMemory is refused with a message that points to the two calls below. SimulationContext.from_yaml() loads the blueprint, and add_egress() adds the sink to it:

docs/snippets/guides/keep_records_in_memory_yaml.py:run
from keep_records_in_memory import show

from desflow import InMemoryEgress, SimulationContext

sink = InMemoryEgress()
app = SimulationContext.from_yaml("keep_records_in_memory.yaml")
app.add_egress(sink)

if __name__ == "__main__":
    app.run()  # until 120, from the blueprint
    show(sink)
docs/snippets/guides/keep_records_in_memory.py:shop
from desflow import InMemoryEgress, SimulationContext


def build_shop(sink: InMemoryEgress) -> SimulationContext:
    """One packer, orders about every 2 seconds, records kept in the sink."""
    app = (
        SimulationContext(sim_id="Shop", factor=0, random_seed=42)
        .add_resource("packers", current_cap=1, max_cap=1)
        .add_service("packing", dist="constant", value=1.5)
        .add_arrival("orders", dist="exponential", rate=0.5)
        # Readings every 30 seconds, as telemetry
        .with_stats("minimal", interval=30)
        .add_egress(sink)
    )

    @app.task(service_id="packing", resource_id="packers")
    def pack_order(task_id: int, entity):
        # The finished event is the order record
        return {"order_id": task_id, "amount": 19.99}

    @app.arrival_loop("orders")
    def orders(context: SimulationContext):
        while True:
            order = yield context.wait_for_arrival("orders")
            context.spawn(pack_order(context.next_instance("pack_order"), entity=order))

    return app


sink = InMemoryEgress()
app = build_shop(sink)

if __name__ == "__main__":
    app.run(until=120)
    show(sink)

setup_egress takes the sink as it takes any other. teardown() hands the sink the records that are still in its buffer, so the script reads the sink after it:

docs/snippets/guides/keep_records_in_memory_low_level.py:shop
from keep_records_in_memory import show

from desflow import InMemoryEgress


def build_shop(sink: InMemoryEgress) -> DynamicRealtimeEnvironment:
    """One packer, orders about every 2 seconds, records kept in the sink."""
    env = DynamicRealtimeEnvironment(factor=0)
    env.registry.register_sim_parameter(PARAMS)
    env.setup_egress([sink])
    # Readings every 30 seconds, as telemetry
    env.setup_stats("Shop", "minimal", interval=30)
    packers = DynamicResource(env, "Shop", "packers")
    env.process(orders(env, packers, Sampler(seed=42)))
    return env


if __name__ == "__main__":
    sink = InMemoryEgress()
    env = build_shop(sink)
    try:
        env.run(until=120)
    finally:
        env.teardown()  # hands the sink the last records
    show(sink)

In the YAML and Builder forms, the run and the reading sit under if __name__ == "__main__":. desflow check, desflow run --sample and desflow test, and the MCP server, import a builder file without running that block. So they check or sample the model without reading a table that no run has filled. desflow run without --sample takes only a blueprint.

Read the Tables

sink.table(name) returns the records of one destination, and sink.tables() returns every destination that holds records. The sink keeps each record in the destination of its stream type:

  • events: one flat row for each event, with its payload as columns, as the Parquet sink writes it. order_id and amount are columns of their own.
  • telemetry: one row for each telemetry record except the step and segment readings, with its path_id and its value. A statistic's value is a double, and here every row is a statistic.
  • steps: the readings of run.steps and run.segments, whose value is a mapping, kept apart from the other telemetry so that each table has one type of value. This shop has neither, so it has no steps table.
  • labels and trace: the records of a sink added with when="labels" or when="trace".

The columns come from every record, so a key that first appears in a later record still gets its column, and it holds null in the rows without it. timestamp is the record's ISO text, as in the files. A destination with no records gives an empty table. The sink empties its tables when a run starts, so a context run twice holds only the second run.

show prints each table, then converts the events to pandas:

docs/snippets/guides/keep_records_in_memory.py:show
import pandas as pd

from desflow import InMemoryEgress


def show(sink: InMemoryEgress) -> None:
    """Prints each table the run filled, and the type of `order_id` in pandas."""
    for name, table in sink.tables().items():
        print(f"{name}: {table.num_rows} rows, {table.num_columns} columns")
    events = sink.table("events")
    # The queued and started events have no order_id, so the column holds nulls
    print("to_pandas():", events.to_pandas()["order_id"].dtype)
    arrow = events.to_pandas(types_mapper=pd.ArrowDtype)
    print("types_mapper=pd.ArrowDtype:", arrow["order_id"].dtype)

Convert to pandas

table.to_pandas() gives a pandas DataFrame with NumPy types. An integer column that holds a null becomes float64, because a NumPy integer has no null. The queued and started events have no order_id, so order_id is float64. table.to_pandas(types_mapper=pd.ArrowDtype) keeps pyarrow's types in pandas, so order_id stays an integer, int64[pyarrow], with the nulls as <NA>.


Check the Result

Save the files of your form from Full Files in a folder of their own, each under the last part of its title. Every form needs keep_records_in_memory.py, which holds show. Run from that folder, each prints the tables and the type of order_id:

The files are keep_records_in_memory.yaml, keep_records_in_memory_yaml.py and keep_records_in_memory.py:

python keep_records_in_memory_yaml.py

The file is keep_records_in_memory.py:

python keep_records_in_memory.py

The files are keep_records_in_memory_low_level.py and keep_records_in_memory.py:

python keep_records_in_memory_low_level.py
1
2
3
4
events: 134 rows, 12 columns
telemetry: 20 rows, 5 columns
to_pandas(): float64
types_mapper=pd.ArrowDtype: int64[pyarrow]

The YAML and Builder forms print these lines. The 134 events are 45 queued, 45 started and 44 finished events, because one order is still being packed when the run ends. The 20 telemetry rows are five readings at each of 30, 60, 90 and 120 seconds: the packers' capacity, in_use, queue_length and utilization, and the task's in_progress. The low-level form prints the same lines with telemetry: 16 rows, because its pack_order is a plain generator, and only a task of the Builder and YAML forms publishes in_progress.


Full Files

Full files
docs/snippets/yaml/keep_records_in_memory.yaml
# The Keep Records in Memory guide: one packer, orders about every 2 seconds, and
# readings every 30 seconds. It names no sink, because a blueprint cannot name
# InMemoryEgress: keep_records_in_memory_yaml.py loads it and adds the sink.
# Run it with: python keep_records_in_memory_yaml.py
simulation: {sim_id: Shop, factor: 0, random_seed: 42}

resources:
  packers: {current_cap: 1, max_cap: 1}

services:
  packing: {dist: constant, value: 1.5}

arrivals:
  orders: {dist: exponential, rate: 0.5, spawn: pack_order}

tasks:
  pack_order:
    service: packing
    resource: packers
    # The finished event is the order record
    payload:
      order_id: {gen: sequence}
      amount: 19.99

# Readings every 30 seconds, as telemetry
stats: {level: minimal, interval: 30}

run: {until: 120}
docs/snippets/guides/keep_records_in_memory_yaml.py
"""The Keep Records in Memory guide, YAML: the blueprint run with an in-memory sink.

A blueprint cannot name InMemoryEgress, so this script loads
keep_records_in_memory.yaml with SimulationContext.from_yaml() and adds the sink with
add_egress(). python keep_records_in_memory_yaml.py runs the blueprint and prints what
keep_records_in_memory.py prints. Both files must be beside it.
"""

# ruff: noqa: E402

import logging

logging.basicConfig(level=logging.WARNING)

from keep_records_in_memory import show

from desflow import InMemoryEgress, SimulationContext

sink = InMemoryEgress()
app = SimulationContext.from_yaml("keep_records_in_memory.yaml")
app.add_egress(sink)

if __name__ == "__main__":
    app.run()  # until 120, from the blueprint
    show(sink)

show is in keep_records_in_memory.py, in the Builder tab.

docs/snippets/guides/keep_records_in_memory.py
"""The Keep Records in Memory guide, builder API: a run's records as pyarrow tables.

The shop runs for two minutes with one packer and keeps its records in an
InMemoryEgress. After the run, the script reads the events and the telemetry as
pyarrow tables and converts the events to pandas, which must be installed
(pip install pandas). python keep_records_in_memory.py prints the tables and the
column types. keep_records_in_memory_yaml.py and keep_records_in_memory_low_level.py
are the same shop from the YAML blueprint and in the low-level API; each imports
`show` from this file, which must be beside it.
"""

# ruff: noqa: E402

import logging

logging.basicConfig(level=logging.WARNING)

import pandas as pd

from desflow import InMemoryEgress


def show(sink: InMemoryEgress) -> None:
    """Prints each table the run filled, and the type of `order_id` in pandas."""
    for name, table in sink.tables().items():
        print(f"{name}: {table.num_rows} rows, {table.num_columns} columns")
    events = sink.table("events")
    # The queued and started events have no order_id, so the column holds nulls
    print("to_pandas():", events.to_pandas()["order_id"].dtype)
    arrow = events.to_pandas(types_mapper=pd.ArrowDtype)
    print("types_mapper=pd.ArrowDtype:", arrow["order_id"].dtype)


from desflow import InMemoryEgress, SimulationContext


def build_shop(sink: InMemoryEgress) -> SimulationContext:
    """One packer, orders about every 2 seconds, records kept in the sink."""
    app = (
        SimulationContext(sim_id="Shop", factor=0, random_seed=42)
        .add_resource("packers", current_cap=1, max_cap=1)
        .add_service("packing", dist="constant", value=1.5)
        .add_arrival("orders", dist="exponential", rate=0.5)
        # Readings every 30 seconds, as telemetry
        .with_stats("minimal", interval=30)
        .add_egress(sink)
    )

    @app.task(service_id="packing", resource_id="packers")
    def pack_order(task_id: int, entity):
        # The finished event is the order record
        return {"order_id": task_id, "amount": 19.99}

    @app.arrival_loop("orders")
    def orders(context: SimulationContext):
        while True:
            order = yield context.wait_for_arrival("orders")
            context.spawn(pack_order(context.next_instance("pack_order"), entity=order))

    return app


sink = InMemoryEgress()
app = build_shop(sink)

if __name__ == "__main__":
    app.run(until=120)
    show(sink)
docs/snippets/guides/keep_records_in_memory_low_level.py
"""The Keep Records in Memory guide, low-level API: the shop with an in-memory sink.

The low-level version of the shop in keep_records_in_memory.py: one packer, orders
about every 2 seconds, and readings every 30 seconds, kept in an
InMemoryEgress. python keep_records_in_memory_low_level.py prints what
keep_records_in_memory.py prints, with its `show`, so that file must be beside it.
"""

# ruff: noqa: E402

import itertools
import logging

from desflow import (
    CapacityConfig,
    DistributionConfig,
    DynamicRealtimeEnvironment,
    DynamicResource,
    Sampler,
    SimParameter,
)

logging.basicConfig(level=logging.WARNING)

PARAMS = SimParameter(
    sim_id="Shop",
    arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)},
    service={"packing": DistributionConfig(dist="constant", value=1.5)},
    resources={"packers": CapacityConfig(current_cap=1, max_cap=1)},
)


def pack_order(env, packers, sampler, key, task_id):
    path_id = "Shop.service.packing"
    env.publish_event(
        key,
        {
            "path_id": path_id,
            "sim_id": "Shop",
            "service": "packing",
            "status": "queued",
        },
        "pack_order",
        task_id,
    )
    with packers.request() as unit:
        yield unit
        env.publish_event(
            key,
            {
                "path_id": path_id,
                "sim_id": "Shop",
                "service": "packing",
                "status": "started",
            },
            "pack_order",
            task_id,
        )
        yield env.timeout(sampler.sample(env.registry.get_config(path_id)))
        # The finished event is the order record
        order = {"order_id": task_id, "amount": 19.99}
        env.publish_event(key, order, "pack_order", task_id)


def orders(env, packers, sampler):
    gap = env.registry.get_config("Shop.arrival.orders")
    for number in itertools.count(1):
        yield env.timeout(sampler.sample(gap))
        env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1))


from keep_records_in_memory import show

from desflow import InMemoryEgress


def build_shop(sink: InMemoryEgress) -> DynamicRealtimeEnvironment:
    """One packer, orders about every 2 seconds, records kept in the sink."""
    env = DynamicRealtimeEnvironment(factor=0)
    env.registry.register_sim_parameter(PARAMS)
    env.setup_egress([sink])
    # Readings every 30 seconds, as telemetry
    env.setup_stats("Shop", "minimal", interval=30)
    packers = DynamicResource(env, "Shop", "packers")
    env.process(orders(env, packers, Sampler(seed=42)))
    return env


if __name__ == "__main__":
    sink = InMemoryEgress()
    env = build_shop(sink)
    try:
        env.run(until=120)
    finally:
        env.teardown()  # hands the sink the last records
    show(sink)

show is in keep_records_in_memory.py, in the Builder tab.