import Foundation import SwiftUI import XCTest @testable import CottonUI /// What a surface costs the phone's main thread when SwiftUI evaluates its /// body. Build 230 (October 2026) crashed on every tap from Home: each tap /// opened a table's list (05b9ea8b1 made every card a route to /// `/lists/[table]`), and evaluating `RecordListSurface.body` overflowed the /// phone's 1 MB main-thread stack — `___chkstk_darwin` hit the stack guard in /// `closure #1 in RecordListSurface.body.getter`, under `ZStack.init`. That /// one closure built the paper screen, everything in its scroll and the /// modifiers around it as values of a single 40 KB type nested 82 levels /// deep, and SwiftUI's view types are resilient, so every one of those values /// is a dynamically sized stack allocation that lives until the closure /// returns. Measured here, one evaluation of that body touched 1.5 MB of /// stack. The simulator's and the Mac's main stacks are 8 MB, which is why /// no walk saw it (build 227's crash, on the old record page's type, hid the /// same way). These guards measure what the phone pays where CI can see it. final class SurfaceStackTests: XCTestCase { /// RULE: a table's list keeps its body small — for every bundled table, the list's view value stays at most 2 KB, its type at most 40 nested generic levels, and one evaluation of its body at most 256 KB of main-thread stack in a debug build (`StackHighWater.surfaceBudget`: a quarter of the phone's 1 MB main stack, the rest held by the frames beneath it — SwiftUI's update recursion, UIKit, the screens below on the stack; debug is the upper bound) — the body is cut into stages (`screen`, `paper`, `column`, `surrounded`, `emptyList`), each built in its own frame and handed on as `AnyView`, and the list is one non-generic type; build 230 held the whole list in one closure (40 KB, 82 levels, 1.5 MB of stack) and crashed on the phone's 1 MB main stack on every list it opened. @MainActor func testEveryBundledTablesListStaysSmallAndShallow() throws { var worst = Worst() for definition in try Self.bundledDefinitions() { let surface = RecordListSurface(definition: definition) { _ in } worst.note(definition.id, body: surface.body) { _ = surface.body } } worst.assertWithin(valueBytes: 2048, depth: 40, stackBytes: StackHighWater.surfaceBudget, of: "list") } /// RULE: the deck a record opens on keeps its body small — for every bundled table, the deck opened at a record stays at most 2 KB as a view value, its type at most 40 nested generic levels, and one evaluation of its body at most 256 KB of main-thread stack in a debug build (`StackHighWater.surfaceBudget`) — every record opens there now, so a deck over that is build 227's and build 230's crash again on the phone's 1 MB main stack. @MainActor func testEveryBundledTablesDeckStaysSmallAndShallow() throws { var worst = Worst() for definition in try Self.bundledDefinitions() { let surface = DeckSurface(definition: definition, filter: [:], view: nil, opensAt: "stack-guard") worst.note(definition.id, body: surface.body) { _ = surface.body } } worst.assertWithin(valueBytes: 2048, depth: 40, stackBytes: StackHighWater.surfaceBudget, of: "deck") } /// RULE: a record's card keeps its body small — for every bundled table's fixture record, the card it is drawn on (`RecordCardFace`, the plain face where its kind has none of its own) stays at most 2 KB as a view value, its type at most 40 nested generic levels, and one evaluation of its body at most 256 KB of main-thread stack in a debug build (`StackHighWater.surfaceBudget`). @MainActor func testEveryBundledTablesCardStaysSmallAndShallow() throws { let bundle = try TestResources.bundle() var worst = Worst() for definition in FixtureDefinitions.load(from: bundle).definitions { for record in try FixtureDefinitions.fixtureRecords(for: definition.id, bundle: bundle).prefix(3) { let face = RecordCardFace(definition: definition, record: record) worst.note(definition.id, body: face.body) { _ = face.body } } } worst.assertWithin(valueBytes: 2048, depth: 40, stackBytes: StackHighWater.surfaceBudget, of: "card") } /// The deepest `<…>` nesting in a type name. static func nesting(of typeName: String) -> Int { var depth = 0 var deepest = 0 for character in typeName { if character == "<" { depth += 1 deepest = max(deepest, depth) } else if character == ">" { depth -= 1 } } return deepest } /// RULE: the depth a guard reads is the deepest run of angle brackets in a type's name. func testNestingCountsTheDeepestAngleBrackets() { XCTAssertEqual(Self.nesting(of: "AnyView"), 0) XCTAssertEqual(Self.nesting(of: "ModifiedContent>, _PaddingLayout>"), 3) } /// RULE: the stack guards assume the PHONE's main-thread stack, 1 MB, and never the test runner's — every budget is a share of `StackHighWater.phoneMainStack` (a surface a quarter, the route chain half), and the runner's own main stack (8 MB on the Mac and the simulator) is only ever the room the measure runs in; the 8 MB stack is why builds 227, 230 and 231 passed every walk and crashed on the phone. func testTheBudgetsAreThePhonesStackNotTheHosts() { XCTAssertEqual(StackHighWater.phoneMainStack, 1 << 20, "an iPhone's main thread has 1 MB of stack") XCTAssertEqual(StackHighWater.surfaceBudget, StackHighWater.phoneMainStack / 4) XCTAssertEqual(StackHighWater.chainBudget, StackHighWater.phoneMainStack / 2) XCTAssertLessThan(StackHighWater.chainBudget, StackHighWater.phoneMainStack) let host = MainActor.assumeIsolated { pthread_get_stacksize_np(pthread_self()) } XCTAssertGreaterThan( host, StackHighWater.phoneMainStack, "the runner's main stack (\(host / 1024) KB) must be larger than the phone's, so a render over the phone's budget is measured and fails by number instead of faulting the run" ) } func testTheMeasureSeesStackUsed() { let shallow = MainActor.assumeIsolated { StackHighWater.measure { _ = Self.descend(16) } } let deep = MainActor.assumeIsolated { StackHighWater.measure { _ = Self.descend(4096) } } XCTAssertGreaterThan(deep, shallow + (64 << 10), "4096 frames read as \(deep) bytes against \(shallow) for 16; the measure must see stack used") XCTAssertLessThan(deep, 4 << 20) } /// Recursion the optimiser cannot fold: every frame holds a buffer it /// writes and reads. @inline(never) private static func descend(_ depth: Int) -> UInt64 { var frame: (UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64) = (UInt64(depth), 1, 2, 3, 4, 5, 6, 7) let sum = withUnsafeMutableBytes(of: &frame) { bytes in bytes.reduce(UInt64(0)) { $0 &+ UInt64($1) } } return depth == 0 ? sum : sum &+ descend(depth - 1) } /// The kit's tables as the core answers a database that took the kit /// (the synthetic household's catalogue, `Resources/Fixtures`): what the /// phone draws, the app bundling no definition of its own. static func bundledDefinitions() throws -> [TableDefinition] { let resources = SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources") let loaded = FixtureDefinitions.load(from: try XCTUnwrap(Bundle(url: resources))) XCTAssertEqual(loaded.failures, []) return loaded.definitions } /// The largest value, deepest type and most stack seen, and whose. struct Worst { var value = (bytes: 0, table: "") var depth = (levels: 0, table: "") var stack = (bytes: 0, table: "") @MainActor mutating func note(_ table: String, body: Body, evaluate: () -> Void) { let bytes = MemoryLayout.size(ofValue: body) let levels = SurfaceStackTests.nesting(of: _typeName(Body.self, qualified: false)) let used = StackHighWater.measure(evaluate) if bytes > value.bytes { value = (bytes, table) } if levels > depth.levels { depth = (levels, table) } if used > stack.bytes { stack = (used, table) } } func assertWithin(valueBytes: Int, depth maxDepth: Int, stackBytes: Int, of surface: String, file: StaticString = #filePath, line: UInt = #line) { print("SurfaceStackTests \(surface): value \(value.bytes) B (\(value.table)), depth \(depth.levels) (\(depth.table)), stack \(stack.bytes / 1024) KB (\(stack.table))") XCTAssertLessThanOrEqual( value.bytes, valueBytes, "\(value.table)'s \(surface) view value is \(value.bytes) bytes; it is copied at every modifier on the phone's 1 MB main stack — build the heavy part in its own function and hand it on as AnyView", file: file, line: line) XCTAssertLessThanOrEqual( depth.levels, maxDepth, "\(depth.table)'s \(surface) view type nests \(depth.levels) generic levels — box the heavy part in AnyView", file: file, line: line) XCTAssertLessThanOrEqual( stack.bytes, stackBytes, "evaluating \(stack.table)'s \(surface) body touched \(stack.bytes / 1024) KB of main-thread stack; the phone has 1 MB for all of SwiftUI (build 230) — cut the body into stages built in their own frames", file: file, line: line) } } }