Configuration Validation Code
Thirty original Python problems on restricted configuration grammars, exact quantities, references, endpoint and resource conflicts, inheritance, overlays and finite policy constraints. Implement explicit validation rules and preserve missing or ambiguous evidence.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Render variable tokens once without executing inserted text
Write
render_config(text,env), env string->string. Match $$ first as one literal dollar, and ${NAME}with ASCII NAME[A-Z_][A-Z0-9_]*. Replace known tokens with exact values WITHOUT rescanning inserted text. Retain unknown tokens and collect sorted distinct missing names. Other dollar syntax stays literal. Return[rendered,missing_names]. Escaped dollars cannot start another token. No mutation.2.Parse literal assignments and report malformed lines
Write
literal_assignments(lines). Strip ASCII space/tab; ignore blank/# lines. Accept ASCII KEY[A-Za-z_][A-Za-z0-9_]*, optional space/tab around =, then VALUE: bare[A-Za-z0-9_./:-]*, single-quoted literal, or double-quoted literal with ONLY backslash-backslash and backslash-quote escapes. Space/tab and #comment may follow. Return[last_value_dict,invalid_line_indices]. No expansion/mutation.3.Parse exact quantities in declared unit families
Write
quantities(values,kind), kind cpu/bytes/time. Accept ONLY ASCII[0-9]+(.[0-9]+)? where dot is literal, followed by a suffix. CPU suffix ""=cores,m=1/1000 core; bytes B,KiB,MiB,GiB use powers of 1024; time ms,s,m,h use seconds. No spaces, signs, exponents or other suffixes. Return reduced[numerator,denominator]per string,Noneif invalid. Leading zeros allowed. No mutation.4.Report wildcard and concrete listener conflicts
Write
listener_conflicts(bindings). Rows[protocol,address,port], protocol tcp/udp, address a canonical IPv4 string or"*", port integer 1..65535. Return[i,j]for every i<j with equal protocol AND port whose addresses are equal or either address is"*". Repeated identical rows still conflict as separate declarations. Keep index-pair order. No mutation.5.Find mount shadows by normalized path components
Write
mount_shadows(paths), absolute slash-separated paths with no .. components. Ignore empty and . components. For each i<j emit[i,j,relation]if normalized paths are equal ("same"), i is a proper ancestor ("first-parent"), or j is ("second-parent"). Root is ancestor of every nonroot path. Whole components must match; preserve index-pair order. This is lexical only. No mutation.6.Check request support and resource limits
Write
resource_checks(rows). Each[requests,limits]maps resource strings to nonnegative integers orNone. Absent/Nonelimit is unbounded. A numeric limit requires a present numeric request, else reason"request"; request>limit gives"limit". Return[row_index,resource,reason]violations, sorted by row then resource. Zero is present. Resources without numeric limits need no request. No mutation.7.Apply opposite percentage rounding to rollout budgets
Write
rollout_budget(replicas,unavailable,surge). replicas>=0 integer; budgets are nonnegative integers or valid 0..100 percent strings. Resolve unavailable percent byfloor(replicas*p/100), surge by ceil. Cap unavailable at replicas; leave surge uncapped. Return[unavailable_count,surge_count,can_progress]; progress iff replicas=0 or either count>0. No minimum-one adjustment or mutation.8.Separate reload changes from immutable-path changes
Write
change_modes(old,new,immutable). Roots are JSON objects; immutable lists string-token paths. Recurse into paired objects; otherwise emit each changed scalar/atomic array or missing member path. Numbers equal by value; bool differs from number, absence from null. Restart iff change and immutable path have either prefix relation; else reload. Return[sorted_reload_paths,sorted_restart_paths].9.Evaluate selectors with absent-key rules
Write
selector_matches(labels,clauses), string->string labels. Every[op,key,values]clause must pass."in": key present AND value in values;"notin": key absent OR value not in values;"exists": key present;"absent": key absent. values ignored for the last two. Empty clausesTrue; empty-string values are present. Use these supplied rules, no coercion or mutation.10.Resolve protocol-specific named target ports
Write
resolve_ports(declarations,queries). Declarations[name,protocol,port], tcp/udp, port 1..65535. Queries[protocol,target], target integer port or name. Integers resolve directly. Names require exactly one matching name/protocol declaration: none means"missing", multiple"ambiguous", even if ports agree. Return[port_or_None,reason_or_None]per query. No digit-string coercion/mutation.11.Audit secret-reference support without payloads
Write
secret_refs(secrets,references). secrets maps names to key->JSON-value maps. References[secret_name,key,optional_bool]. A reference resolves iff both secret and key exist, even if value is null or empty string. Return [resolved_indices,missing_required_indices,missing_optional_indices], preserving every reference occurrence. Return no secret values and do not mutate.12.Count the encoded bytes of every configuration record
Write
payload_budget(entries,budget), entries[string_name,string_value], neither containing NUL; budget>=0 integer. A record encodes name+"="+value+NUL as UTF-8. Count every occurrence, including duplicate names and empty strings. Return[total_bytes,total_bytes<=budget,per_record_byte_sizes]. Do not print values, count characters as bytes, deduplicate or mutate.13.Choose the longest whole-segment route before priority ties
Write
route_targets(routes,paths). Routes[normalized_absolute_prefix,integer_priority,string_backend]; paths normalized absolute, no trailing slash except root. Prefix matches equality or full leading path segments; root matches all. Choose most prefix segments, then greatest priority, then earliest route index. Return[index,backend]orNoneper path. Do not use raw startswith alone or mutate.14.Report uncovered IPv4 ranges as a minimal ordered CIDR cover
Write
network_gaps(network,allowed), valid IPv4 CIDR strings. Normalize host bits away. Return minimal CIDRs covering addresses in network but in NO allowed network, sorted by starting address. Clip allowed ranges to the requested network and merge overlaps/adjacency. Every address counts, including network/broadcast endpoints. Do not enumerate all addresses; /0 is allowed. No mutation.15.Validate a restricted immutable artifact-reference grammar
Write
artifact_pins(values). Accept exactly NAME@sha256:DIGEST. NAME matches ASCII[a-z0-9][a-z0-9./:_-]*; DIGEST is exactly 64 lowercase hexadecimal characters. Return[NAME,DIGEST]per accepted string,Noneotherwise. Registry port colons are permitted by this grammar; tags without a digest are not pins. Do not trim, lowercase or interpret a broader registry syntax. No mutation.16.Intersect numeric tuple-version constraints
Write
version_intersection(ranges). Each[lower,upper]bound isNoneor[major,minor,patch]nonnegative integers. Lower inclusive, upper exclusive;Noneis unbounded. Return[greatest_lower,least_upper], orNoneif finite lower>=upper. Empty ranges returns[None,None]. Compare integer tuples lexicographically, not dotted strings. Bounds may themselves describe an empty range. No mutation.17.Apply ordered network rules with port bounds
Write
network_decisions(rules,queries). Rules[allow_bool,IPv4_CIDR,low_port,high_port], inclusive valid port range. Queries[IPv4_address,port]. Normalize network host bits; first rule containing address AND port decides. Return[allow_bool,rule_index]per query; no match gives[False,None]. Do not reorder by specificity, deduplicate rules or perform network actions. No mutation.18.Merge object overlays with member deletion
Write
object_overlay(target,patch)for JSON values. Nonobject patch REPLACES target, even null. Object patch starts from a copy of object target, otherwise {}; each null member deletes its key, each object member overlays recursively, other members replace whole values. Arrays are atomic. Return a detached result without changing either input. No text-format preservation.19.Resolve ordered profile inheritance using C3 precedence
Write
profile_order(profiles,root), <=10 string profiles mapping to ordered parent-name lists. Return root's C3 linearization, using the starter rules, orNonefor a reachable missing profile, duplicate parent, cycle or inconsistent merge. Unrelated invalid profiles do not matter. No implicit object/base profile is added. Include root first and each inherited name once. No mutation.20.Check HTTPS components against a host-port policy
Write
endpoint_allowed(urls,allowed), lowercase host->integer ports. Reject ASCII controls/space/DEL, parse errors, non-HTTPS/relative URLs, absent host, any userinfo or any # marker. Use urlsplit hostname and port (443 when parsed port isNone); accept iff host/port is allowed. Return booleans. No DNS, escape decoding, broader URL-safety claim or mutation.21.Mask permissions and preserve special bits
Write
masked_modes(values,umask), umask integer 0..511. Accept exactly 3 or 4 ASCII octal digits per string. Preserve requested 07000 special bits; clear umask bits from requested 0777 permissions. Return[four_digit_octal,flags]per valid string,Noneotherwise. Flags ordered setuid,setgid,sticky for bits 04000,02000,01000. Bit arithmetic only; no filesystem calls or mutation.22.Check distinct writable volume owners
Write
volume_writers(volumes,mounts). volumes maps names to"single"/"shared". Mounts[workload,volume,writable_bool], string IDs. Report unknown-volume mount indices. For each known single volume with >1 DISTINCT writable workload, report[volume,sorted_workloads], sorted by volume. Read-only adds no writer; repeated mounts count once per writer. Return[unknown_indices,conflicts]. No mutation.23.Match exactly one extra label for wildcard hostname metadata
Write
hostname_matches(hosts,patterns). Inputs are ASCII DNS names, optional final dot; patterns exact names or"*.suffix". Lowercase and remove one final dot. Exact patterns require equality; wildcard requires EXACTLY one extra nonempty label before suffix. Return matching pattern indices per host in pattern order, retaining repeated patterns. No DNS/TLS verification or mutation.24.Expand one bounded schedule field
Write
cron_field(text,low,high), 0<=low<=high<=59. Comma terms: *, one ASCII integer, or a-b. Star/range may add /positive_step, anchored at their start; a single integer cannot use /. Inclusive bounds require low<=a<=b<=high. No whitespace, signs, empty terms or Unicode digits. Return sorted union, orNoneif ANY term is invalid. Leading zeros allowed. One field only; no mutation.25.Check nominal probe cadence and deadline
Write
probe_budget(initial,period,timeout,failures,budget): nonnegative integer initial/budget; positive integer period/timeout/failures. Nominal starts: initial+k*period, k=0..failures-1. Last finish=start+timeout. Return[last_finish,timeout<=period,last_finish<=budget]. Equality is allowed. Supplied arithmetic only; no actual orchestrator runtime guarantee or mutation.26.Account for node overhead and workload replicas
Write
placement_budget(nodes,workloads). nodes maps names to[CPU_capacity,memory_capacity,CPU_overhead,memory_overhead]. Workloads[unique_id,node,replicas,CPU_each,memory_each]; nonnegative counts. Used=overhead+all replicas. Return[node_records,unknown_workload_ids], records sorted[node,CPU_used,memory_used,exceeded_resources], labels CPU then memory, strict >. Unknown IDs retain order.27.Resolve lexical includes without escaping the workspace root
Write
include_paths(base,paths). base is canonical relative directory or "". Includes are relative slash-separated strings. Ignore empty/. components; .. pops, rejecting immediately above workspace root. Reject leading / or NUL. Return canonical relative paths, root as".", orNoneper rejection. Backslash/percent escapes stay literal. Each path starts from base. No filesystem/symlink checks.29.Negotiate unambiguous versions and shared capabilities
Write
negotiate_caps(client,server,required). Rows[nonnegative_integer_version,string_feature_list]. Exclude any version repeated on EITHER endpoint, even identical rows. For common unique versions intersect feature sets; require all required features. Return[highest_feasible_version,sorted_shared_features], orNone. Duplicate feature strings add nothing. No mutation.30.Find the lexical feasible Boolean profile
Write
complete_flags(names,clauses,fixed), <=12 unique string names. Each clause lists[known_name,wanted_bool]literals: OR within, AND across clauses. fixed maps known names to bool orNone(free). Return sorted [[name,value]] for the lexicographically smallest feasible Boolean vector (FalsebeforeTrue), orNone. An empty clause is false; no clauses impose no rule. No mutation.