Part III — Advanced Systems · Chapter 16 · Lesson 1 of 6 · 12 min read
Lesson 1: DataType, Field, Schema, DataFrame, and LazyFrame
Lesson level: Advanced
Purpose: Learn the five building blocks of PeaLang’s data foundation and how they fit together: data types describe values, fields name them, schemas describe tables, DataFrames hold tables in memory, and LazyFrames describe work to be done on tables before any data is touched.
Release note: module paths (std.data), type names, and method names in this chapter follow the illustrative PeaLang v0.63 RC2 data foundation. Verify them against the data reference before publishing or teaching from this material.
Learning objectives
By the end of this lesson you will be able to:
- list the built-in data types and choose the right one for each column;
- declare fields with names, types, and nullability;
- build schemas explicitly and compare, extend, and validate them;
- create DataFrames from rows and columns, and inspect their shape and schema;
- explain the difference between eager DataFrame operations and deferred LazyFrame plans;
- read a LazyFrame plan and predict when work actually happens.
1.1 Why a data foundation?
Chapters 5 and 8 used lists and maps for collections of records. That works for dozens of rows. It breaks down for thousands or millions: every row repeats its keys, every value can be any type, and every operation is a hand-written loop. Mistakes such as a missing key or a number stored as a string surface late, deep inside a calculation.
The data foundation replaces a list of maps with a table: a set of named, typed columns of equal length. Because each column has one type, the runtime can check operations before running them, store values compactly, and apply whole-column operations instead of per-row loops. And because tables have schemas, they fit naturally with the typed contracts from Chapter 15.
// Before: list of maps
let orders = [
{ "id": 1, "region": "north", "amount": 120.5 },
{ "id": 2, "region": "south", "amount": "80" }, // wrong type, unnoticed
{ "id": 3, "regoin": "north", "amount": 42.0 }, // misspelled key, unnoticed
]
// After: a DataFrame with a schema
import std.data as d
let orders_df = d.DataFrame.from_rows(orders, schema: d.Schema([
d.Field("id", d.Int64),
d.Field("region", d.Utf8),
d.Field("amount", d.Float64),
]))
// SchemaError: row 1, field "amount": expected Float64, got Utf8 "80"
The schema version fails immediately and points to the exact row and field. That is the theme of this chapter: say what the data is, and let the foundation hold you to it.
1.2 DataType: the vocabulary of columns
A DataType describes the values a column may hold. The data foundation provides a fixed set of types, each with a defined portable representation so tables can cross host boundaries.
| DataType | Holds | Portable form | Notes |
|---|---|---|---|
| Bool | true or false | boolean | |
| Int64 | 64-bit signed integers | number or string | Values outside ±2^53 travel as strings to JavaScript hosts |
| Float64 | IEEE 754 double | number | Never use for money |
| Decimal(p, s) | Exact decimals, precision p, scale s | string | Use for money; Decimal(18, 2) is a common choice |
| Utf8 | Text | string | |
| Date | Calendar date, no time zone | ISO date string | Matches LocalDate from Chapter 15 |
| Timestamp(unit, tz) | Instant with a unit (ms, us) | RFC 3339 string | tz is "UTC" or null for naive values |
| Duration(unit) | Elapsed time | integer count of units | |
| Categorical | Text from a small repeated set | string | Stored as codes; fast grouping |
| List(T) | A list of T per row | list | |
| Struct(fields) | A nested record per row | map | Field names fixed by the type |
| Null | Only null | null | Type of an all-null column before inference |
Every type except Null can also hold nulls if the field allows it. Nullability belongs to the field, not the type, which section 1.3 explains.
import std.data as d
let money = d.Decimal(18, 2)
let event_time = d.Timestamp("ms", "UTC")
let tags = d.List(d.Utf8)
let address = d.Struct([
d.Field("city", d.Utf8),
d.Field("postcode", d.Utf8, nullable: true),
])
print money // Decimal(18, 2)
print event_time // Timestamp(ms, UTC)
print tags.inner // Utf8
print money.is_numeric // true
1.3 Field: name, type, and nullability
A Field binds a column name to a data type and states whether nulls are allowed. Fields may also carry metadata, such as a description or a unit, which tools display but operations ignore.
let f_id = d.Field("order_id", d.Int64) // not nullable by default
let f_note = d.Field("note", d.Utf8, nullable: true)
let f_amount = d.Field("amount", d.Decimal(18, 2),
metadata: { "unit": "EUR", "description": "Gross order value" })
print f_id.nullable // false
print f_amount.metadata["unit"] // EUR
let renamed = f_amount.with_name("gross_amount")
let relaxed = f_id.with_nullable(true)
Fields are immutable values. Methods such as with_name and with_nullable return new fields, which makes schemas safe to share between modules.
Field names must be non-empty and unique within a schema. They are case-sensitive: Amount and amount are different fields, which is a common source of join failures when data comes from different systems. Section 1.4 shows how to catch this early.
Why nullability lives on the field. The same type may be required in one table and optional in another. An Int64 order ID is required in an orders table but optional as parent_order_id. Keeping nullability on the field lets both share the type while keeping different rules.
1.4 Schema: the shape of a table
A Schema is an ordered list of fields. It is the contract for a table, in the same sense that the Chapter 15 contracts described function inputs and outputs.
let order_schema = d.Schema([
d.Field("order_id", d.Int64),
d.Field("customer_id", d.Utf8),
d.Field("region", d.Categorical),
d.Field("ordered_at", d.Timestamp("ms", "UTC")),
d.Field("amount", d.Decimal(18, 2)),
d.Field("note", d.Utf8, nullable: true),
])
print order_schema.names // ["order_id", "customer_id", "region", ...]
print order_schema.len // 6
print order_schema["amount"].dtype // Decimal(18, 2)
print order_schema.index_of("region") // 2
Schemas support the operations you need to evolve and compare table shapes:
let with_status = order_schema.append(d.Field("status", d.Categorical))
let slim = order_schema.select(["order_id", "amount"])
let no_note = order_schema.drop(["note"])
let diff = order_schema.diff(with_status)
print diff
// added: status: Categorical
// removed: (none)
// changed: (none)
// Case-insensitive collision check before joining data from another system
let issues = order_schema.lint(case_insensitive_unique: true)
for issue in issues { print issue }
Schema equality is strict: same names, same order, same types, and same nullability. When order does not matter, use a.equivalent(b), which ignores field order. When a table only needs to contain certain fields, use a.satisfies(b), which checks that every field in b exists in a with a compatible type.
Validating data against a schema. schema.validate(rows) returns a report rather than throwing at the first problem. Use it at ingestion boundaries to decide whether to reject a whole file or quarantine bad rows.
let report = order_schema.validate(raw_rows, max_errors: 100)
if not report.ok {
print str.format("{} invalid rows of {}", report.invalid_count, report.row_count)
for e in report.errors.take(5) {
print str.format("row {}: {} — {}", e.row, e.field, e.message)
}
}
1.5 DataFrame: a table in memory
A DataFrame is an immutable, in-memory table: a schema plus one column of values per field, all of the same length. Every operation returns a new DataFrame, so a DataFrame passed to a function can never be changed behind your back.
Creating DataFrames. There are three common constructors. Pass a schema whenever you know one; inference is covered in Lesson 2.
// From rows (list of maps)
let df = d.DataFrame.from_rows([
{ "order_id": 1, "region": "north", "amount": "120.50" },
{ "order_id": 2, "region": "south", "amount": "80.00" },
{ "order_id": 3, "region": "north", "amount": "42.00" },
], schema: d.Schema([
d.Field("order_id", d.Int64),
d.Field("region", d.Categorical),
d.Field("amount", d.Decimal(18, 2)),
]))
// From columns (map of lists) — faster for large data
let df2 = d.DataFrame.from_columns({
"order_id": [1, 2, 3],
"region": ["north", "south", "north"],
"amount": ["120.50", "80.00", "42.00"],
}, schema: df.schema)
// Empty, with a schema — useful as a starting accumulator
let empty = d.DataFrame.empty(df.schema)
Decimal values are given as strings, exactly as in the Chapter 15 contracts. Passing 120.5 as a float to a Decimal column is rejected unless you opt in with coerce: "float_to_decimal", which rounds half-to-even and records a warning.
Inspecting DataFrames.
print df.shape // (3, 3) — rows, columns
print df.height // 3
print df.columns // ["order_id", "region", "amount"]
print df.schema // Schema(order_id: Int64, region: Categorical, amount: Decimal(18, 2))
print df.head(2)
// ┌──────────┬────────┬────────┐
// │ order_id │ region │ amount │
// │ Int64 │ Cat │ Dec(2) │
// ├──────────┼────────┼────────┤
// │ 1 │ north │ 120.50 │
// │ 2 │ south │ 80.00 │
// └──────────┴────────┴────────┘
let amounts = df.column("amount") // a Series
print amounts.dtype // Decimal(18, 2)
print amounts.sum() // 242.50
print amounts.null_count // 0
let first = df.row(0) // { "order_id": 1, "region": "north", "amount": "120.50" }
for row in df.iter_rows() { /* row is a map */ }
A column on its own is a Series: a name, a type, and values. Series support whole-column operations such as sum, mean, min, unique, and comparisons that produce Boolean series. Lesson 3 uses them as building blocks for filters and calculated columns.
Avoid row loops. iter_rows exists for output and debugging. For calculations, use column operations: they are type-checked once per column rather than once per value, and they run inside the runtime’s optimized kernels instead of the interpreter loop. On a million-row table, the difference is typically one to two orders of magnitude.
Resource limits still apply. A DataFrame counts against max_memory_bytes and max_collection_items from Chapter 14. A host that embeds data-heavy scripts should set these deliberately; the defaults suit record-at-a-time rules, not tables.
1.6 LazyFrame: describing work before doing it
A LazyFrame does not hold data. It holds a plan: a source plus a chain of operations. Nothing runs until you call collect(). This sounds like a small difference, but it lets the runtime see the whole computation at once and make it cheaper before it starts.
let plan = d.scan_csv("data/orders.csv", schema: order_schema) // no file read yet
.filter(d.col("region") == "north")
.select(["order_id", "amount"])
.sort("amount", descending: true)
.limit(10)
print plan.explain()
// LIMIT 10
// SORT amount DESC (top-k: 10)
// SCAN CSV data/orders.csv
// projection: [order_id, region, amount]
// predicate: region == "north"
let top = plan.collect() // now the file is read, once
Read the explained plan from the bottom up. The optimizer has made three changes you did not write:
- Projection pushdown. Only the three columns the plan needs are parsed from the file; customer_id, ordered_at, and note are skipped.
- Predicate pushdown. The region filter runs while scanning, so rows from other regions are never materialized.
- Top-k sort. Because a limit follows the sort, the engine keeps only the ten largest values instead of sorting the whole table.
An equivalent eager pipeline — read_csv, then filter, then select, then sort, then head — would load every column of every row and sort all northern orders before discarding all but ten.
Moving between the two. Any DataFrame can become a LazyFrame with df.lazy(), and any LazyFrame becomes a DataFrame with collect(). Both share the same operation names, so code moves easily between them.
let summary = orders_df.lazy()
.group_by("region")
.agg([d.col("amount").sum().alias("total"), d.count().alias("orders")])
.collect()
Schema before data. A LazyFrame knows its output schema without running. plan.schema computes the schema of every step, so type errors appear when the plan is built, not halfway through a large file.
let bad = d.scan_csv("data/orders.csv", schema: order_schema)
.filter(d.col("amount") > "100") // comparing Decimal with Utf8
// PlanError: filter: cannot compare Decimal(18, 2) with Utf8 literal "100"
// hint: use d.lit_decimal("100.00")
1.7 Choosing between DataFrame and LazyFrame
| Situation | Prefer | Why |
|---|---|---|
| Exploring small data interactively in the REPL | DataFrame | Immediate results; easy to inspect each step |
| Reading files larger than a few megabytes | LazyFrame | Pushdown avoids parsing unused columns and rows |
| Long pipelines with filters after joins | LazyFrame | Optimizer reorders filters before joins where safe |
| Values passed to a host function or returned from an export | DataFrame | Hosts receive data, not plans |
| Reusing an intermediate result several times | DataFrame (collect once) | Avoids recomputing the plan for each use |
| Running inside tight resource limits | LazyFrame | Streaming execution keeps peak memory lower |
A practical rule: start lazy, collect once, at the end. Collect early only when an intermediate result is reused or must be inspected.
1.8 Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Using Float64 for money | Rounding drift in totals and joins on amounts | Use Decimal(p, s) and pass values as strings |
| Relying on inference for production inputs | Column types change when a file’s first rows change | Declare the schema; use inference only to draft it |
| Making every field nullable "to be safe" | Missing values pass silently into calculations | Allow nulls only where the business allows absence |
| Looping over iter_rows for calculations | Slow pipelines; per-value type checks | Use column expressions and Series operations |
| Collecting a LazyFrame repeatedly | The same file is read and parsed many times | Collect once into a DataFrame and reuse it |
| Ignoring case differences in field names | Joins and selects fail or match the wrong column | Run schema.lint(case_insensitive_unique: true) at ingestion |
| Leaving default resource limits for data scripts | Valid workloads hit memory or collection limits | Set limits for data workloads deliberately in the host |
Guided practice
- Define a schema for a payments table with payment_id, order_id, paid_at (UTC, ms), amount (Decimal 18,2), method (Categorical), and an optional reference.
- Create a DataFrame of five payments from rows. Introduce one bad row and read the validation report.
- Print shape, schema, and head(3), then compute the sum and null count of amount.
- Build a LazyFrame that scans a CSV, keeps card payments over 50.00, and selects three columns. Print explain() and identify each pushdown.
- Use schema.diff to compare your payments schema with a version that adds currency.
Hands-on lab
Create a small data module, sales_model.pea, that exports schemas for three tables: customers, orders, and order lines. Include at least one Decimal, one Timestamp, one Categorical, one nullable field, and one Struct. Write a loader that reads each table from CSV with its schema, validates it, and writes a validation summary. Then build one LazyFrame plan that answers "top five customers by order value in the last 30 days" and capture its explained plan.
Deliverable: sales_model.pea, the three sample CSV files (including at least three deliberately invalid rows), the validation summary output, and the explained plan with a short note naming each optimization you see.
Review questions
- What is the difference between a DataType and a Field?
- Why does nullability belong to the field rather than the type?
- What is the difference between schema equality, equivalence, and satisfaction?
- Why are Decimal values passed as strings when creating a DataFrame?
- What does a LazyFrame hold, and when does it do work?
- Name three optimizations that a LazyFrame plan can apply and explain each.
- When is collecting early the right choice?
Applied challenge
A host passes your script a list of 200,000 order maps from a legacy system. Some amounts are numbers, some are strings, a few are null, and field names vary in case between batches. Design an ingestion function that normalizes names, validates against your schema, quarantines bad rows into a second DataFrame with a reason column, and returns both. Measure memory use against a 64 MiB limit and explain the design choices that keep it within budget.
Lesson summary
PeaLang’s data foundation turns loosely typed collections into tables with contracts. DataTypes describe values, including exact Decimal and time-zone-aware Timestamp types. Fields add names and nullability. Schemas describe whole tables and support comparison, evolution, and validation reports. DataFrames hold immutable, column-oriented data with fast whole-column operations. LazyFrames describe plans that are type-checked before execution and optimized with projection pushdown, predicate pushdown, and top-k sorting. Start lazy, collect once, and declare schemas wherever data enters the system.
Transition to Lesson 2
This lesson declared every schema by hand. Real data often arrives without one. Lesson 2 covers schema inference and interchange with CSV, JSON, and JSONL: how inference decides on types, how to control it, and how to read and write files without losing precision or time-zone information.
Lesson status: Ready for review.