PeaBox Lab › PeaLang › Learn › Chapter 16 › Lesson 1

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:

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.

DataTypeHoldsPortable formNotes
Booltrue or falseboolean
Int6464-bit signed integersnumber or stringValues outside ±2^53 travel as strings to JavaScript hosts
Float64IEEE 754 doublenumberNever use for money
Decimal(p, s)Exact decimals, precision p, scale sstringUse for money; Decimal(18, 2) is a common choice
Utf8Textstring
DateCalendar date, no time zoneISO date stringMatches LocalDate from Chapter 15
Timestamp(unit, tz)Instant with a unit (ms, us)RFC 3339 stringtz is "UTC" or null for naive values
Duration(unit)Elapsed timeinteger count of units
CategoricalText from a small repeated setstringStored as codes; fast grouping
List(T)A list of T per rowlist
Struct(fields)A nested record per rowmapField names fixed by the type
NullOnly nullnullType 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:

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

SituationPreferWhy
Exploring small data interactively in the REPLDataFrameImmediate results; easy to inspect each step
Reading files larger than a few megabytesLazyFramePushdown avoids parsing unused columns and rows
Long pipelines with filters after joinsLazyFrameOptimizer reorders filters before joins where safe
Values passed to a host function or returned from an exportDataFrameHosts receive data, not plans
Reusing an intermediate result several timesDataFrame (collect once)Avoids recomputing the plan for each use
Running inside tight resource limitsLazyFrameStreaming 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

MistakeConsequenceFix
Using Float64 for moneyRounding drift in totals and joins on amountsUse Decimal(p, s) and pass values as strings
Relying on inference for production inputsColumn types change when a file’s first rows changeDeclare the schema; use inference only to draft it
Making every field nullable "to be safe"Missing values pass silently into calculationsAllow nulls only where the business allows absence
Looping over iter_rows for calculationsSlow pipelines; per-value type checksUse column expressions and Series operations
Collecting a LazyFrame repeatedlyThe same file is read and parsed many timesCollect once into a DataFrame and reuse it
Ignoring case differences in field namesJoins and selects fail or match the wrong columnRun schema.lint(case_insensitive_unique: true) at ingestion
Leaving default resource limits for data scriptsValid workloads hit memory or collection limitsSet limits for data workloads deliberately in the host

Guided practice

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

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.

← Previous Next →