"""Small pure functions on immutable records; no imports, I/O or mutable globals.

Domain and policy are declared in requirements.md. Tags are retained values,
not globally unique identifiers. Only record[0] is a sorting key.
"""


def stable_sort(records):
    result = []
    for record in records:
        position = len(result)
        while position > 0 and record[0] < result[position - 1][0]:
            position -= 1
        result.insert(position, record)
    return tuple(result)


def drop_duplicates(records):
    # Defect: preserve the set of values, but discard repeated occurrences.
    unique = []
    for record in records:
        if record not in unique:
            unique.append(record)
    return stable_sort(tuple(unique))


def empty_output(records):
    # Defect: sortedness and idempotence alone permit this output.
    return ()


def unstable_sort(records):
    # Seeded defect: <= inserts new equal-key records before earlier ones.
    result = []
    for record in records:
        position = len(result)
        while position > 0 and record[0] <= result[position - 1][0]:
            position -= 1
        result.insert(position, record)
    return tuple(result)
