swift

Seeded Swift defects — UI off the main actor, uncancelled Tasks, retain cycles, force unwraps.

16 deliberate defects, each with a marker naming the rule in standards/ it breaks. It measures recall: how many of the defects the reviewer flags at their severity or higher. The pass condition is that all 10 BLOCKER defects are flagged.

Because each marker names a rule, the scorer also grades attribution. A reviewer that finds the bug but cites the wrong rule counts as caught, and separately as misattributed.

Running it

Nothing here is ever merged. Open a throwaway pull request on a pilot repository already onboarded for this stack, adding this directory and seeded/clean together, wait for the automated review to finish, then score it.

seed-canary.yml does exactly this on a schedule and closes the pull request afterwards, including when the run fails.

terminal
$ GH_TOKEN=... npx redlinegate metrics score-seeds --repo <org>/<repo> --pr <n>

Flags and output are on redline metrics.

The 16 defects

SeedSeverityRule it violatesDefect
1BLOCKERcore/hardcoded-secretshardcoded credential
2BLOCKERswift/sensitive-data-in-userdefaultsauth token stored in UserDefaults instead of the Keychain
3BLOCKERcore/customer-data-in-logscustomer identifier in logs
4BLOCKERswift/force-operationsforce-unwrapped optional in a production path
5BLOCKERswift/retain-cyclestrong self captured in an escaping closure stored by the object
6BLOCKERswift/force-operationsforce try
7BLOCKERswift/ui-off-main-actorUI mutated off the main actor
8BLOCKERswift/blocking-main-threadsynchronous network call on the main thread
9BLOCKERswift/uncancelled-taskunstructured Task with no cancellation path
10BLOCKERcore/type-checker-suppressionlinter suppression with no explanation and no ticket
1HIGHswift/concurrency-checking-opt-outunchecked Sendable over an unguarded dictionary
2HIGHswift/implicitly-unwrapped-declarationcrashes far from the missing assignment
3HIGHswift/unowned-capturecrashes if the response outlives the screen
4HIGHswift/strong-delegatedelegate retained strongly, leaking the controller
5HIGHswift/copying-reduce-accumulatorquadratic string building
11HIGHcore/untracked-todoplaceholder with no ticket reference

Scoring

The score reports BLOCKER recall, false positives, and rule attribution. The canary appends it to data/seed-scores.jsonl and fails the run if BLOCKER recall drops below 1.0 or the clean corpus attracts a false positive. Of the 16 defects here, 10 BLOCKER and 6 HIGH — only the BLOCKER count is a pass condition.

Adding a defect

Add the code and one marker line above it. The format, and what scripts/validate.mjs checks, are on Seeded corpus.

The full file

seeded/swift/AntiSlop.swift · 29 lines · 1.0 KB
// DO NOT MERGE — Redline validation seed (anti-slop rules).
import UIKit

// SEED 1 [HIGH] (swift/concurrency-checking-opt-out) unchecked Sendable over an unguarded dictionary
final class ImageCache: @unchecked Sendable {
    var images: [URL: UIImage] = [:]
}

final class ProfileViewController: UIViewController {
    // SEED 2 [HIGH] (swift/implicitly-unwrapped-declaration) crashes far from the missing assignment
    var viewModel: ProfileViewModel!

    func load() {
        // SEED 3 [HIGH] (swift/unowned-capture) crashes if the response outlives the screen
        api.fetchProfile { [unowned self] result in
            self.title = try? result.get().name
        }
    }
}

protocol ProfileServiceDelegate { func didLoad(_ p: Profile) }
final class ProfileService {
    // SEED 4 [HIGH] (swift/strong-delegate) delegate retained strongly, leaking the controller
    var delegate: ProfileServiceDelegate?
}

// SEED 5 [HIGH] (swift/copying-reduce-accumulator) quadratic string building
let hex = Data().reduce("") { $0 + String(format: "%02x", $1) }
seeded/swift/SeededViolations.swift · 63 lines · 2.3 KB
// DO NOT MERGE — Redline validation seed.
// Every `SEED n [SEVERITY] (rule-id)` marker must be flagged at that severity or higher,
// citing that rule id. Score with scripts/score-seeds.mjs.
import Foundation
import UIKit

final class SeededViolations {

    // SEED 1 [BLOCKER] (core/hardcoded-secrets) hardcoded credential
    private let apiKey = "acme-live-7Fq2Rd9Km4Tz6Hb3Vy8Wn"

    private var handlers: [() -> Void] = []
    private let label = UILabel()

    func load(msisdn: String) {
        // SEED 2 [BLOCKER] (swift/sensitive-data-in-userdefaults) auth token stored in UserDefaults instead of the Keychain
        UserDefaults.standard.set(apiKey, forKey: "authToken")

        // SEED 3 [BLOCKER] (core/customer-data-in-logs) customer identifier in logs
        print("loading balance for \(msisdn)")

        let url = URL(string: "https://api.internal/balance/\(msisdn)")!
        // SEED 4 [BLOCKER] (swift/force-operations) force-unwrapped optional in a production path

        URLSession.shared.dataTask(with: url) { data, _, _ in
            // SEED 5 [BLOCKER] (swift/retain-cycle) strong self captured in an escaping closure stored by the object
            self.handlers.append { print("done") }

            // SEED 6 [BLOCKER] (swift/force-operations) force try
            let decoded = try! JSONDecoder().decode([String: String].self, from: data!)

            // SEED 7 [BLOCKER] (swift/ui-off-main-actor) UI mutated off the main actor
            self.label.text = decoded["balance"]
        }.resume()

        // SEED 8 [BLOCKER] (swift/blocking-main-thread) synchronous network call on the main thread
        let blocking = try? Data(contentsOf: url)
        _ = blocking
    }

    // SEED 9 [BLOCKER] (swift/uncancelled-task) unstructured Task with no cancellation path
    func refresh() {
        Task {
            while true {
                load(msisdn: "0000")
            }
        }
    }
}

extension SeededViolations {

    // SEED 10 [BLOCKER] (core/type-checker-suppression) linter suppression with no explanation and no ticket
    // swiftlint:disable force_cast
    func coerce(_ value: Any) -> String {
        return value as! String
    }

    // SEED 11 [HIGH] (core/untracked-todo) placeholder with no ticket reference
    // TODO: decide whether the scanner should follow symlinks
    func pending() {}
}