When collecting, deduplicating, and truncating algorithm outputs (e.g., “top N” items, merged references, ranked suggestions), enforce determinism and configuration-consistent clipping.
Rules: 1) Never truncate by slicing an unordered container.
set for deduplication, do not slice it directly (hash iteration order is nondeterministic).2) Make clipping logic configuration-aware and intent-preserving.
final_clip_factor) to halve results.3) Prefer bounded iteration over recursion for repair loops.
while loop with a max-iteration/termination condition rather than recursion.Example (ordered dedupe + safe truncation with mixed-source intent):
MAX_TICKETS = 3
def merge_and_truncate(github_like_links, asana_links, max_tickets=MAX_TICKETS):
seen = set()
merged = []
def add_links(links):
for link in links:
if link not in seen:
seen.add(link)
merged.append(link)
# Deterministic: use input order (first-seen order)
# Intent-preserving: reserve at least one slot for Asana if present
github_like_links = list(github_like_links)
asana_links = list(asana_links)
reserved_for_asana = 1 if asana_links else 0
add_links(github_like_links[: max_tickets - reserved_for_asana])
add_links(asana_links[: reserved_for_asana])
return merged[:max_tickets]
Example (bounded iterative JSON repair):
import json
def fix_json_message(json_message, max_iter=10):
for _ in range(max_iter):
try:
return json.loads(json_message)
except Exception:
# apply one corrective step to json_message
# (e.g., replace offending char at computed index)
# then continue
pass
return {}
Adopting these rules prevents flaky behavior in production (nondeterministic truncation), avoids surprising drops relative to configuration intent, and keeps “repair” algorithms safe from stack overflows or runaway recursion.