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.
# 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.pysimulation:{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:packingresource:packers# The finished event is the order recordpayload:order_id:{gen:sequence}amount:19.99# Readings every 30 seconds, as telemetrystats:{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:
fromkeep_records_in_memoryimportshowfromdesflowimportInMemoryEgress,SimulationContextsink=InMemoryEgress()app=SimulationContext.from_yaml("keep_records_in_memory.yaml")app.add_egress(sink)if__name__=="__main__":app.run()# until 120, from the blueprintshow(sink)
fromdesflowimportInMemoryEgress,SimulationContextdefbuild_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")defpack_order(task_id:int,entity):# The finished event is the order recordreturn{"order_id":task_id,"amount":19.99}@app.arrival_loop("orders")deforders(context:SimulationContext):whileTrue:order=yieldcontext.wait_for_arrival("orders")context.spawn(pack_order(context.next_instance("pack_order"),entity=order))returnappsink=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:
fromkeep_records_in_memoryimportshowfromdesflowimportInMemoryEgressdefbuild_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 telemetryenv.setup_stats("Shop","minimal",interval=30)packers=DynamicResource(env,"Shop","packers")env.process(orders(env,packers,Sampler(seed=42)))returnenvif__name__=="__main__":sink=InMemoryEgress()env=build_shop(sink)try:env.run(until=120)finally:env.teardown()# hands the sink the last recordsshow(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:
importpandasaspdfromdesflowimportInMemoryEgressdefshow(sink:InMemoryEgress)->None:"""Prints each table the run filled, and the type of `order_id` in pandas."""forname,tableinsink.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 nullsprint("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:
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.
# 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.pysimulation:{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:packingresource:packers# The finished event is the order recordpayload:order_id:{gen:sequence}amount:19.99# Readings every 30 seconds, as telemetrystats:{level:minimal, interval:30}run:{until:120}
"""The Keep Records in Memory guide, YAML: the blueprint run with an in-memory sink.A blueprint cannot name InMemoryEgress, so this script loadskeep_records_in_memory.yaml with SimulationContext.from_yaml() and adds the sink withadd_egress(). python keep_records_in_memory_yaml.py runs the blueprint and prints whatkeep_records_in_memory.py prints. Both files must be beside it."""# ruff: noqa: E402importlogginglogging.basicConfig(level=logging.WARNING)fromkeep_records_in_memoryimportshowfromdesflowimportInMemoryEgress,SimulationContextsink=InMemoryEgress()app=SimulationContext.from_yaml("keep_records_in_memory.yaml")app.add_egress(sink)if__name__=="__main__":app.run()# until 120, from the blueprintshow(sink)
show is in keep_records_in_memory.py, in the Builder tab.
"""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 anInMemoryEgress. After the run, the script reads the events and the telemetry aspyarrow tables and converts the events to pandas, which must be installed(pip install pandas). python keep_records_in_memory.py prints the tables and thecolumn types. keep_records_in_memory_yaml.py and keep_records_in_memory_low_level.pyare 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: E402importlogginglogging.basicConfig(level=logging.WARNING)importpandasaspdfromdesflowimportInMemoryEgressdefshow(sink:InMemoryEgress)->None:"""Prints each table the run filled, and the type of `order_id` in pandas."""forname,tableinsink.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 nullsprint("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)fromdesflowimportInMemoryEgress,SimulationContextdefbuild_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")defpack_order(task_id:int,entity):# The finished event is the order recordreturn{"order_id":task_id,"amount":19.99}@app.arrival_loop("orders")deforders(context:SimulationContext):whileTrue:order=yieldcontext.wait_for_arrival("orders")context.spawn(pack_order(context.next_instance("pack_order"),entity=order))returnappsink=InMemoryEgress()app=build_shop(sink)if__name__=="__main__":app.run(until=120)show(sink)
"""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, ordersabout every 2 seconds, and readings every 30 seconds, kept in anInMemoryEgress. python keep_records_in_memory_low_level.py prints whatkeep_records_in_memory.py prints, with its `show`, so that file must be beside it."""# ruff: noqa: E402importitertoolsimportloggingfromdesflowimport(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)},)defpack_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,)withpackers.request()asunit:yieldunitenv.publish_event(key,{"path_id":path_id,"sim_id":"Shop","service":"packing","status":"started",},"pack_order",task_id,)yieldenv.timeout(sampler.sample(env.registry.get_config(path_id)))# The finished event is the order recordorder={"order_id":task_id,"amount":19.99}env.publish_event(key,order,"pack_order",task_id)deforders(env,packers,sampler):gap=env.registry.get_config("Shop.arrival.orders")fornumberinitertools.count(1):yieldenv.timeout(sampler.sample(gap))env.process(pack_order(env,packers,sampler,f"orders-{number}",number-1))fromkeep_records_in_memoryimportshowfromdesflowimportInMemoryEgressdefbuild_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 telemetryenv.setup_stats("Shop","minimal",interval=30)packers=DynamicResource(env,"Shop","packers")env.process(orders(env,packers,Sampler(seed=42)))returnenvif__name__=="__main__":sink=InMemoryEgress()env=build_shop(sink)try:env.run(until=120)finally:env.teardown()# hands the sink the last recordsshow(sink)
show is in keep_records_in_memory.py, in the Builder tab.