Skip to content
Merged
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ xcuserdata/
DerivedData/
*.xcodeproj
Package.resolved
/Benchmarks/.build
/Benchmarks/.swiftpm
/Benchmarks/.benchmarkBaselines
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ Read `CONSTRAINTS.md` before writing code. Do not weaken it to make a change pas
## Build and test
- `swift build` and `swift test`; one test with `swift test --filter <Suite>/<test>`. Pipe through `xcsift` (configured in `.xcsift.toml`) for compact errors.
- CI (`.github/workflows/ci.yml`) runs macOS and Linux on Swift 6.0, 6.1 and 6.2: code must compile on 6.0 with only the standard library.
- Format before handing back Swift changes: `swift-format format --in-place --parallel --recursive Sources Tests Package.swift Architecture` (config in `.swift-format`). Use the Swift 6.3 toolchain's swift-format (`swiftly run swift-format … +6.3`): the format check runs 6.3, and other versions wrap lines differently.
- Format before handing back Swift changes: `swift-format format --in-place --parallel --recursive Sources Tests Package.swift Architecture Benchmarks` (config in `.swift-format`). Use the Swift 6.3 toolchain's swift-format (`swiftly run swift-format … +6.3`): the format check runs 6.3, and other versions wrap lines differently.
- Architecture rules: `swift test --package-path Architecture` (macOS only) runs the mechanical part of `CODING_STANDARDS.md` and `CONSTRAINTS.md` as [swift-llm-check](https://github.com/mackoj/swift-llm-check) rules, listed in `docs/architecture-rules.md`. A failure prints the rule, why it exists and how to fix it: fix the code, never add a baseline. A new or changed rule needs its rationale and bad and good examples, a `DetectorTests` case, and `LLM_CHECK_RECORD=1 swift test --package-path Architecture` to regenerate the document.
- Benchmarks: `swift package --package-path Benchmarks benchmark` (package-benchmark; README, "Benchmarks"). A change made for speed or memory states its before and after from `benchmark baseline compare main` in the pull request; a change to a hot path (JSON parsing or printing, evaluation, mutation, `OrderedDictionary`) checks it did not regress. `Benchmarks/scripts/profile.sh '<name>'` shows where a benchmark spends its time.
- Pull requests also run `.github/workflows/soundness.yml`: swiftlang's soundness checks (format, DocC with warnings as errors, API breakage against the base branch, YAML lint, shellcheck, broken symlinks) plus actionlint and zizmor on the workflows. A deliberate API break is called out in the pull request.
- For a differential run against Sextant, set `SEXTANT_ORACLE_LOG` as described in the README's Tests section.

Expand Down
160 changes: 160 additions & 0 deletions Benchmarks/Benchmarks/JSONPathBenchmarks/JSONPathBenchmarks.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import Benchmark
import Foundation
import JSONPath

/// The documents the benchmarks read: the compliance test suite the tests run, and a generated store far larger than
/// the README's, to show costs that grow with size.
enum Fixtures {
/// `Tests/JSONPathTests/Fixtures/cts.json`, 232 KB of real-world JSON: long strings, deep nesting, escapes.
static let ctsText: String = {
let url = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
.deletingLastPathComponent().appendingPathComponent("Tests/JSONPathTests/Fixtures/cts.json")
return try! String(contentsOf: url, encoding: .utf8)
}()

static let cts: JSONValue = try! JSONValue(parsing: ctsText)

/// The README's bookstore with `books` books, each with nested reviews: about 1.4 MB of JSON for 5,000 books.
static func storeText(books: Int = 5_000) -> String {
let categories = ["reference", "fiction", "poetry", "history"]
let items = (0..<books).map { index in
"""
{"category": "\(categories[index % categories.count])", "author": "Author \(index % 97)", \
"title": "Title \(index) \\u00e9\\n", "isbn": "0-\(index)-21311-3", "price": \(Double(index % 40) + 0.99), \
"available": \(index % 3 != 0), "reviews": [{"stars": \(index % 5 + 1), "by": "r\(index)"}, \
{"stars": \((index + 2) % 5 + 1), "by": "s\(index)", "tags": ["a", "b", null]}]}
"""
}
return """
{"store": {"book": [\(items.joined(separator: ","))], \
"bicycle": {"color": "red", "price": 399.99}}, "expensive": 10}
"""
}

static let largeText = storeText()
static let large: JSONValue = try! JSONValue(parsing: largeText)
}

/// Expressions in both Dialects, from simple to every kind of segment and selector.
let rfcExpressions = [
"$.store.book[0].title", "$['store']['book'][*]['author']", "$..author", "$.store.book[-1:0:-2]",
"$..book[?@.price < 10 && @.category == 'fiction'].title", "$..book[?match(@.isbn, '0-1.*')]",
"$.store.book[?count(@.reviews[?@.stars > 3]) > 1]", "$..*",
]
let jaywayExpressions = [
"$.store.book[0].title", "$['store']['book'][*]['author']", "$..author", "$.store.book[-2:]",
"$..book[?(@.price < 10 && @.category == 'fiction')].title", "$..book[?(@.isbn =~ /0-1.*/)]",
"$.store.book[?(@.reviews.length() > 1)]", "$..book.length()",
]

/// A Codable model of one book.
struct Book: Codable {
struct Review: Codable {
var stars: Int
var by: String
var tags: [String?]?
}
var category: String
var author: String
var title: String
var isbn: String
var price: Double
var available: Bool
var reviews: [Review]
}

let benchmarks: @Sendable () -> Void = {
Benchmark.defaultConfiguration = .init(
metrics: [.wallClock, .cpuTotal, .mallocCountTotal, .peakMemoryResident, .retainCount],
// Exact counts and microseconds, so a change of a few percent shows up in a comparison.
timeUnits: .microseconds,
units: [.mallocCountTotal: .count, .retainCount: .count],
maxDuration: .seconds(2),
maxIterations: 1_000
)

// MARK: JSON text

Benchmark("Parse JSON, compliance suite") { _ in
blackHole(try JSONValue(parsing: Fixtures.ctsText))
}
Benchmark("Parse JSON, large") { _ in
blackHole(try JSONValue(parsing: Fixtures.largeText))
}
Benchmark("Parse JSON from bytes, large") { benchmark in
let bytes = Array(Fixtures.largeText.utf8)
benchmark.startMeasurement()
blackHole(try JSONValue(parsing: bytes))
}
Benchmark("Print JSON, large") { _ in
blackHole(Fixtures.large.jsonString)
}
Benchmark("Print JSON pretty and sorted, large") { _ in
blackHole(Fixtures.large.jsonString(prettyPrinted: true, sortedKeys: true))
}

// MARK: Parsing paths

Benchmark("Parse paths, RFC 9535") { _ in
for expression in rfcExpressions { blackHole(try JSONPath(expression)) }
}
Benchmark("Parse paths, Jayway") { _ in
for expression in jaywayExpressions { blackHole(try JSONPath(expression, dialect: .jayway)) }
}

// MARK: Queries

for (dialect, expressions) in [(JSONPath.Dialect.rfc9535, rfcExpressions), (.jayway, jaywayExpressions)] {
let name = dialect == .rfc9535 ? "RFC 9535" : "Jayway"
let paths = expressions.map { try! JSONPath($0, dialect: dialect) }
Benchmark("Query \(name), every expression, large") { _ in
for path in paths { blackHole(try path.values(in: Fixtures.large)) }
}
Benchmark("Query \(name), descendants, large") { _ in
blackHole(try paths[2].values(in: Fixtures.large))
}
Benchmark("Query \(name), filter, large") { _ in
blackHole(try paths[4].values(in: Fixtures.large))
}
Benchmark("Query \(name), nodes with normalized paths, large") { _ in
blackHole(try paths[1].nodes(in: Fixtures.large))
}
}
let everything = try! JSONPath("$..*")
Benchmark("Query RFC 9535, every node, compliance suite") { _ in
blackHole(try everything.values(in: Fixtures.cts))
}

// MARK: Pointers and mutation

let pointers = (0..<1_000).map { try! JSONPointer("/store/book/\($0 * 5)/reviews/1/by") }
Benchmark("Resolve JSON pointers, large") { _ in
for pointer in pointers { blackHole(pointer.resolve(in: Fixtures.large)) }
}
let prices = try! JSONPath("$..price")
Benchmark("Replace every price, large") { benchmark in
var document = Fixtures.large
benchmark.startMeasurement()
blackHole(try document.replace(prices, with: 1))
blackHole(document)
}
let unavailable = try! JSONPath("$.store.book[?@.available == false]")
Benchmark("Remove filtered books, large") { benchmark in
var document = Fixtures.large
benchmark.startMeasurement()
blackHole(try document.remove(unavailable))
blackHole(document)
}

// MARK: Codable

let books = try! JSONPath("$.store.book[*]").values(in: Fixtures.large)
Benchmark("Decode books, large") { _ in
blackHole(try JSONValueDecoder().decode(Book.self, from: books))
}
let decoded = try! JSONValueDecoder().decode(Book.self, from: books)
Benchmark("Encode books, large") { _ in
blackHole(try JSONValueEncoder().encode(decoded))
}
}
31 changes: 31 additions & 0 deletions Benchmarks/Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// swift-tools-version: 6.1
import PackageDescription

// swift-jsonpath's benchmarks, on ordo-one/package-benchmark (https://www.swift.org/blog/benchmarks/). A separate
// package so the benchmark dependency and Foundation stay out of the library's dependency budget. Run from the
// repository root: `swift package --package-path Benchmarks benchmark`.
let package = Package(
name: "Benchmarks",
platforms: [.macOS(.v15)],
dependencies: [
.package(name: "swift-jsonpath", path: ".."),
.package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.38.0"),
],
targets: [
.executableTarget(
name: "JSONPathBenchmarks",
dependencies: [
.product(name: "Benchmark", package: "package-benchmark"),
.product(name: "JSONPath", package: "swift-jsonpath"),
],
path: "Benchmarks/JSONPathBenchmarks",
plugins: [
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
]
),
// Reads two `benchmark --format markdown` outputs and prints each benchmark's p50 before and after.
.executableTarget(name: "p50", path: "Tools/P50"),
// Reads an exported Time Profiler table and prints the hottest functions (scripts/profile.sh).
.executableTarget(name: "hotspots", path: "Tools/Hotspots"),
]
)
86 changes: 86 additions & 0 deletions Benchmarks/Tools/Hotspots/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import Foundation

// Usage: swift run --package-path Benchmarks hotspots profile.xml [count]
// profile.xml is `xcrun xctrace export --xpath '…/table[@schema="time-profile"]'` (scripts/profile.sh writes it).
// Prints the functions with the most samples of their own (self) and the library functions with the most samples
// under them (inclusive). package-benchmark's ARC counting hooks are left out: they exist only while measuring.

/// Reads the rows of an exported time-profile table. Frames and backtraces are written once and then referenced
/// by id, so both are remembered.
final class ProfileReader: NSObject, XMLParserDelegate {
var frameNames: [String: String] = [:]
var backtraces: [String: [String]] = [:]
var samples: [[String]] = []
private var current: [String]?
private var currentID: String?

func parser(
_ parser: XMLParser, didStartElement element: String, namespaceURI: String?, qualifiedName: String?,
attributes: [String: String] = [:]
) {
switch element {
case "tagged-backtrace", "backtrace":
if let ref = attributes["ref"] {
samples.append(backtraces[ref] ?? [])
} else {
current = []
currentID = attributes["id"]
}
case "frame" where current != nil:
if let ref = attributes["ref"] {
current?.append(frameNames[ref] ?? "?")
} else {
let name = attributes["name"] ?? "?"
if let id = attributes["id"] { frameNames[id] = name }
current?.append(name)
}
default:
break
}
}

func parser(_ parser: XMLParser, didEndElement element: String, namespaceURI: String?, qualifiedName: String?) {
guard element == "tagged-backtrace" || element == "backtrace", let frames = current else { return }
if let currentID { backtraces[currentID] = frames }
samples.append(frames)
current = nil
currentID = nil
}
}

let arguments = CommandLine.arguments
guard arguments.count >= 2, let parser = XMLParser(contentsOf: URL(fileURLWithPath: arguments[1])) else {
print("usage: hotspots <profile.xml> [count]")
exit(2)
}
let count = arguments.count > 2 ? Int(arguments[2]) ?? 20 : 20
let reader = ProfileReader()
parser.delegate = reader
guard parser.parse() else {
print("could not read \(arguments[1]): \(parser.parserError.map { "\($0)" } ?? "unknown error")")
exit(1)
}

let measuring = /ARCStatsProducer|_swift_(retain|release)_(adapter|hook)|MallocInterposer/
func short(_ name: String) -> String { String(name.prefix { $0 != "(" }.suffix(110)) }

var selfSamples: [String: Int] = [:]
var inclusiveSamples: [String: Int] = [:]
var total = 0
for frames in reader.samples where !frames.isEmpty {
guard !frames.contains(where: { $0.contains(measuring) }) else { continue }
total += 1
selfSamples[short(frames[0]), default: 0] += 1
for name in Set(frames.map(short)) where name.contains(/JSONPath/) {
inclusiveSamples[name, default: 0] += 1
}
}
func report(_ title: String, _ counts: [String: Int], of total: Int) {
print(title)
for (name, samples) in counts.sorted(by: { $0.value > $1.value }).prefix(count) {
print(String(format: "%5.1f%% ", 100 * Double(samples) / Double(max(total, 1))) + name)
}
}
print("\(total) samples")
report("Self", selfSamples, of: total)
report("Inclusive (JSONPath)", inclusiveSamples, of: total)
54 changes: 54 additions & 0 deletions Benchmarks/Tools/P50/main.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Foundation

// Usage: swift run --package-path Benchmarks p50 before.md after.md
// Each file is the output of `swift package --package-path Benchmarks benchmark --format markdown --no-progress`.

/// A benchmark's p50 wall clock in microseconds and p50 malloc count.
struct Medians {
var wallClock: Double?
var mallocs: Double?
}

func medians(inFile path: String) throws -> [(name: String, medians: Medians)] {
let text = try String(contentsOfFile: path, encoding: .utf8)
// A row: | Time (wall clock) (μs) * | p0 | p25 | p50 | … The unit is absent for plain counts.
let row =
/^\|\s*(Malloc \(total\)|Time \(wall clock\))\s*(?:\(([^)]*)\))?\s*\*?\s*\|\s*[\d,]+\s*\|\s*[\d,]+\s*\|\s*([\d,]+)/
let scale: [String: Double] = ["ns": 1e-3, "μs": 1, "us": 1, "ms": 1e3, "s": 1e6, "K": 1e3, "M": 1e6]
var result: [(name: String, medians: Medians)] = []
for line in text.split(separator: "\n") {
if line.hasPrefix("### ") {
let name = line.dropFirst(4).replacingOccurrences(of: " metrics", with: "")
result.append((name, Medians()))
} else if let match = line.firstMatch(of: row), !result.isEmpty {
let value =
Double(match.3.replacingOccurrences(of: ",", with: ""))! * (match.2.map { scale[String($0)] ?? 1 } ?? 1)
if match.1 == "Malloc (total)" {
result[result.count - 1].medians.mallocs = result[result.count - 1].medians.mallocs ?? value
} else {
result[result.count - 1].medians.wallClock = result[result.count - 1].medians.wallClock ?? value
}
}
}
return result
}

let arguments = CommandLine.arguments
guard arguments.count == 3 else {
print("usage: p50 <before.md> <after.md>")
exit(2)
}
let before = Dictionary(
try medians(inFile: arguments[1]).map { ($0.name, $0.medians) }, uniquingKeysWith: { a, _ in a })
func cell(_ old: Double?, _ new: Double?, _ format: String) -> String {
guard let new else { return "" }
guard let old else { return String(format: format, new) }
return String(format: "\(format) → \(format) (%.2fx)", old, new, new / old)
}
print("| Benchmark | Wall clock p50 (µs) | Mallocs p50 |")
print("|---|---|---|")
for (name, after) in try medians(inFile: arguments[2]) {
let old = before[name]
print(
"| \(name) | \(cell(old?.wallClock, after.wallClock, "%.1f")) | \(cell(old?.mallocs, after.mallocs, "%.0f")) |")
}
23 changes: 23 additions & 0 deletions Benchmarks/scripts/profile.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#!/bin/sh
# Profiles one benchmark with Instruments' Time Profiler and prints its hottest functions.
# Usage, from the repository root: Benchmarks/scripts/profile.sh 'Query RFC 9535, descendants, large' [count]
# The name is the benchmark's, matched exactly. The trace is kept in Benchmarks/.build/profiles to open in Instruments.
set -eu

name=$1
count=${2:-20}
package=$(cd "$(dirname "$0")/.." && pwd)
swift build --package-path "$package" -c release --product JSONPathBenchmarks
swift build --package-path "$package" -c release --product hotspots
bin=$(swift build --package-path "$package" -c release --show-bin-path)

out="$package/.build/profiles"
mkdir -p "$out"
trace="$out/$(echo "$name" | tr -c 'A-Za-z0-9' '-').trace"
rm -rf "$trace"
# Instruments symbolicates only a binary launched by its absolute path.
xcrun xctrace record --quiet --template 'Time Profiler' --output "$trace" --launch -- \
"$bin/JSONPathBenchmarks" --filter "^$name\$"
xcrun xctrace export --input "$trace" \
--xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]' > "$trace.xml"
"$bin/hotspots" "$trace.xml" "$count"
2 changes: 1 addition & 1 deletion CONSTRAINTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Run these before handing back a code change; each must pass.
| Diff integrity | 0 whitespace errors | `git diff --check main` |
| Compilation | 0 errors, debug and release | `swift build --build-tests` and `swift build -c release` |
| Behaviour | 0 failing tests, including all 715 compliance cases, the Sextant suite and README examples | `swift test` |
| Formatting | 0 changes from formatting, 0 lint findings, with swift-format 6.3 | `swift-format lint --strict --parallel --recursive Sources Tests Package.swift Architecture` |
| Formatting | 0 changes from formatting, 0 lint findings, with swift-format 6.3 | `swift-format lint --strict --parallel --recursive Sources Tests Package.swift Architecture Benchmarks` |
| Architecture rules | 0 findings from the rules in `docs/architecture-rules.md`, no baseline, and the rules document up to date | `swift test --package-path Architecture` (macOS) |
| Public API | 0 breaking changes against the base branch, unless intended and called out in the pull request | `swift package diagnose-api-breaking-changes main` |
| Documentation | 0 DocC warnings for the `.spi.yml` targets | Soundness workflow's documentation check (CI) |
Expand Down
Loading
Loading