From 43ecd36c0e7314ebe1e5da2d6e6f26522d298f93 Mon Sep 17 00:00:00 2001 From: CoolBoy Date: Thu, 12 Nov 2026 03:10:51 +0800 Subject: [PATCH] feat: improve route throughput and reconcile delayed validation outcomes --- README.md | 58 +++++++++ modelhub_submmit_api/failure_log_inspector.py | 1 + modelhub_submmit_api/failure_taxonomy.py | 1 + modelhub_submmit_api/main.py | 31 +++-- modelhub_submmit_api/market_intelligence.py | 4 + modelhub_submmit_api/modelhub_client.py | 38 ++++-- modelhub_submmit_api/outcome_tracker.py | 49 +++++++- modelhub_submmit_api/profile_admission.py | 51 ++++++-- modelhub_submmit_api/routing_engine.py | 103 +++++++-------- modelhub_submmit_api/state_sync.py | 2 +- modelhub_submmit_api/version.py | 2 +- tests/test_outcome_reconciliation.py | 118 ++++++++++++++++++ tests/test_throughput_routing.py | 93 ++++++++++++++ 13 files changed, 468 insertions(+), 83 deletions(-) create mode 100644 tests/test_outcome_reconciliation.py create mode 100644 tests/test_throughput_routing.py diff --git a/README.md b/README.md index fc6342bdc2..9320bde8d2 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,64 @@ This repository is packaged for the ModelHub XC agent platform. +## Evidence-throughput scheduler (2026.11.12.1) + +New submissions use `evidence_throughput_v2` by default, without LLM calls. +Eligible model routes are retained through batch admission instead of discarding +all but the top route before profile limits are checked. A blocked first choice +can yield to a qualified alternate GPU. At most one route per model is selected +per batch, and a successfully submitted model is excluded from later batches in +the same run. Existing six-route discovery limits and framework prerequisite +checks remain; this release does not enumerate every framework/config variant. + +Exact quantization-signature evidence takes precedence over family statistics. +Sparse feedback is shrunk toward bounded broader evidence rather than switching +sources abruptly at 20/40/100 samples. Public/local overlapping populations are +not added together as independent observations. These are heuristic regularized +estimates and Wilson-style bounds, not calibrated Bayesian credible intervals. +Recent platform failures reduce operational ranking without architecture bans. + +The default unproven-profile budget remains two, but rises to four for qualified, +valid official configurations with at least 300 public samples and a public +Wilson lower bound of 0.60, absent adverse exact/family evidence. Proven exact +profiles retain the existing cap exemption. These are configurable-in-code +initial operating choices, not empirically established optimal thresholds. +Only the requested batch consumes provisional profile budget; alternatives and +unselected candidates do not consume it. Deferred candidates remain retryable. + +Fixed five-point ranking bins and the probability-squared formula are removed. +Quality frontiers are anchored within three percentage points of the best +remaining adjusted lower bound. Within a frontier, expected successes/hour is +used only if every duration estimate is explicitly validated; otherwise quality +orders the frontier. Current total-based platform queue estimates are unvalidated +and do not receive fictitious 36-hour defaults. Automatic validated duration +estimation and execution-version-specific statistical migration are not included +in this release. No historic validation jobs are cancelled on migration. + +## Outcome feedback recovery 2026.11.12.1 + +History reads now continue through an empty page rather than trusting platform +page counts, deduplicate task IDs, and fail on non-progress or malformed pages. +Outcome synchronization requires successful reads from every account before +advancing its cursor. A 24-hour overlap refreshes known tasks; older unknown +terminal rows are not re-imported over a compact checkpoint. + +Each successful synchronization additionally reconciles up to four pending models +without time filters, rotating by a persisted check timestamp (15-minute minimum +recheck interval). Only known pending IDs are imported from these lookups. Missing +tasks are never treated as finished. This recovers late results and feeds existing +architecture blocks, exact-profile statistics and pending-route limits. The +rotation marker survives state synchronization and container restarts. History +reads are bounded at 1,000 pages per query and explicitly fail rather than reporting +partial history as complete. + +Host container-runtime executables missing on the platform are classified as +infrastructure failures, not model incompatibility. Tokenizer-patch image names +are recognized before the generic vLLM fallback. No success-rate admission gates, +GPU ranking, age reserves or queue-cancellation rules are relaxed. These changes +repair feedback collection; improved validation success still requires observing +new terminal outcomes after deployment. + ## Capacity pagination verification 2026.10.28.1 Supersedes the 2026.10.27.1 policy of using the larger reported total. diff --git a/modelhub_submmit_api/failure_log_inspector.py b/modelhub_submmit_api/failure_log_inspector.py index a6db0f199f..db5effd0da 100644 --- a/modelhub_submmit_api/failure_log_inspector.py +++ b/modelhub_submmit_api/failure_log_inspector.py @@ -41,6 +41,7 @@ TARGET_DOCKER_IMAGE_PATTERN = re.compile( re.IGNORECASE, ) FRAMEWORK_IMAGE_MARKERS = ( + ("vllm_tokenizer_patch", ("vllm-tokenizer-patch", "vllm_tokenizer_patch")), ("vllm-customized", ("vllm-customized", "vllm_customized")), ("vllm_fix_tokenizer", ("vllm-fix-tokenizer", "vllm_fix_tokenizer")), ("sentence-transformers", ("sentence-transformers", "sentence_transformers")), diff --git a/modelhub_submmit_api/failure_taxonomy.py b/modelhub_submmit_api/failure_taxonomy.py index ee4ba1c6fe..6ea37a9889 100644 --- a/modelhub_submmit_api/failure_taxonomy.py +++ b/modelhub_submmit_api/failure_taxonomy.py @@ -64,6 +64,7 @@ SEMANTIC_POLICIES: dict[str, FailureClassification] = { } PLATFORM_PATTERNS = ( + (re.compile(r"fork/exec\s+/[^\n]*container-runtime:\s*no such file or directory", re.I), "missing_host_container_runtime"), (re.compile(r"welcome\.sh: No such file|data: command not found", re.I), "broken_platform_launch_script"), (re.compile(r"id_rsa.*No such file", re.I), "missing_platform_credential"), (re.compile(r"找不到空闲卡|no idle (?:gpu|card)", re.I), "no_idle_device"), diff --git a/modelhub_submmit_api/main.py b/modelhub_submmit_api/main.py index c2347cebb5..50e5c380e3 100644 --- a/modelhub_submmit_api/main.py +++ b/modelhub_submmit_api/main.py @@ -1699,7 +1699,10 @@ def run_submission( capacity_saturated = False if args.dry_run: - attempted_candidates = diversified_candidates[:target_submit_count] + attempted_candidates = filter_profile_batch( + diversified_candidates, outcome_tracker.pending_records(), outcome_tracker.get_stats_report(), + max_selected=target_submit_count, + )[0] else: claim_store = SubmissionClaimStore( Path(getattr(args, "claims_path", DEFAULT_CLAIMS_PATH)), @@ -1718,28 +1721,38 @@ def run_submission( # already-scanned pool until the desired number of real submissions is # reached or account capacity is genuinely exhausted. while len(submitted) < target_submit_count and len(attempted_candidates) < max_submit_attempts: + submitted_models = {row["repoId"] for row in submitted} remaining_candidates = [ candidate for candidate in diversified_candidates if candidate_key(candidate) not in attempted_keys + and candidate["repoId"] not in submitted_models and not submission_exclusion_store.is_blocked(candidate["repoId"], candidate["targetGpu"]) ] - remaining_candidates = one_candidate_per_model(remaining_candidates) - remaining_candidates, profile_deferred = filter_profile_batch( - remaining_candidates, outcome_tracker.pending_records(), profile_stats, - ) - for candidate in profile_deferred: - attempted_keys.add(candidate_key(candidate)) - skipped.append({"repoId": candidate["repoId"], "targetGpu": candidate["targetGpu"], - "reason": "profile_feedback_deferred", "deferred": True}) desired_count = min( target_submit_count - len(submitted), max_submit_attempts - len(attempted_candidates), ) if state_sync is not None: desired_count = min(desired_count, int(state_sync.batch_size)) + remaining_candidates, profile_deferred = filter_profile_batch( + remaining_candidates, outcome_tracker.pending_records(), profile_stats, + max_selected=desired_count, + ) + for candidate in profile_deferred: + attempted_keys.add(candidate_key(candidate)) + skipped.append({"repoId": candidate["repoId"], "targetGpu": candidate["targetGpu"], + "reason": "profile_feedback_deferred", "deferred": True}) batch_candidates = claim_store.claim(remaining_candidates, limit=desired_count) + claimed_keys = {candidate_key(candidate) for candidate in batch_candidates} + for candidate in remaining_candidates: + if candidate_key(candidate) not in claimed_keys: + attempted_keys.add(candidate_key(candidate)) + skipped.append({"repoId": candidate["repoId"], "targetGpu": candidate["targetGpu"], + "reason": "route_claim_deferred", "deferred": True}) if not batch_candidates: + if remaining_candidates: + continue # A claimed first choice must not hide alternatives. break attempted_candidates.extend(batch_candidates) attempted_keys.update(candidate_key(candidate) for candidate in batch_candidates) diff --git a/modelhub_submmit_api/market_intelligence.py b/modelhub_submmit_api/market_intelligence.py index 77dbe623be..b8449793cc 100644 --- a/modelhub_submmit_api/market_intelligence.py +++ b/modelhub_submmit_api/market_intelligence.py @@ -833,6 +833,8 @@ class MarketIntelligenceManager: "localScore": local_score if local_samples else None, "recentLocalSamples": recent_samples, "recentLocalSuccessRate": recent_rate, + "recentPlatformFailures": max(0, int(recent_item.get("platformFailureCount") or 0)), + "recentTerminalSamples": recent_success + recent_all_failures, "consecutiveLocalFailures": consecutive_failures, "consecutivePlatformFailures": consecutive_platform_failures, "circuitOpen": circuit_open, @@ -1008,6 +1010,8 @@ class MarketIntelligenceManager: "frameworkLocalSuccessRate": evidence["localSuccessRate"], "frameworkRecentLocalSamples": evidence["recentLocalSamples"], "frameworkRecentLocalSuccessRate": evidence["recentLocalSuccessRate"], + "frameworkRecentPlatformFailures": evidence["recentPlatformFailures"], + "frameworkRecentTerminalSamples": evidence["recentTerminalSamples"], "frameworkConsecutiveLocalFailures": evidence["consecutiveLocalFailures"], "frameworkCombinedScore": evidence["combinedScore"], "frameworkMarketQualified": evidence["publicQualified"], diff --git a/modelhub_submmit_api/modelhub_client.py b/modelhub_submmit_api/modelhub_client.py index a2f683c56f..02ef62da99 100644 --- a/modelhub_submmit_api/modelhub_client.py +++ b/modelhub_submmit_api/modelhub_client.py @@ -216,7 +216,8 @@ class ModelHubClient: ) -> list[dict[str, Any]]: current = 1 records: list[dict[str, Any]] = [] - while True: + seen: set[str] = set() + while current <= 1000: page = self.list_tasks_page( current=current, page_size=page_size, @@ -228,16 +229,26 @@ class ModelHubClient: status=status, verify_result=verify_result, ) - page_data = page.get("data") or {} - page_records = page_data.get("records") or [] - records.extend(page_records) + page_data = page.get("data") + if not isinstance(page_data, dict) or not isinstance(page_data.get("records"), list): + raise ModelHubAPIError("Invalid task history page") + page_records = page_data["records"] + if not page_records: + return records + before = len(seen) + for task in page_records: + if not isinstance(task, dict) or not task.get("taskId"): + raise ModelHubAPIError("Invalid task history record") + task_id = str(task["taskId"]) + if task_id not in seen: + seen.add(task_id) + records.append(task) + if len(seen) == before: + raise ModelHubAPIError("Task history pagination made no progress") if max_records > 0 and len(records) >= max_records: return records[:max_records] - pages = int(page_data.get("pages") or 0) - if pages <= current or not page_records: - break current += 1 - return records + raise ModelHubAPIError("Task history pagination budget exhausted") def add_task(self, payload: dict[str, Any]) -> dict[str, Any]: return self._request("POST", "/api/adapt/task/add", data=payload) @@ -923,17 +934,26 @@ class ModelHubClientPool: # Default: use only the reader client to avoid fanout amplification. # The fanout_all parameter allows explicit cross-account merging when needed. fanout_all = kwargs.pop("_fanout_all", False) + strict = kwargs.pop("_strict", False) if not fanout_all: + if strict: + return self._reader.list_tasks(**kwargs) return self._safe_list_tasks(self._reader, kwargs) merged: list[dict[str, Any]] = [] seen: set[str] = set() with ThreadPoolExecutor(max_workers=min(len(self.clients), 12)) as executor: - futures = {executor.submit(self._safe_list_tasks, client, kwargs): index for index, client in enumerate(self.clients)} + futures = { + (executor.submit(client.list_tasks, **kwargs) if strict else + executor.submit(self._safe_list_tasks, client, kwargs)): index + for index, client in enumerate(self.clients) + } for future in as_completed(futures): try: tasks = future.result() except Exception: + if strict: + raise ModelHubAPIError("Incomplete cross-account task history") from None tasks = [] for task in tasks: task_id = str(task.get("taskId")) if task.get("taskId") is not None else None diff --git a/modelhub_submmit_api/outcome_tracker.py b/modelhub_submmit_api/outcome_tracker.py index 3243e8a735..777e8fb7ee 100644 --- a/modelhub_submmit_api/outcome_tracker.py +++ b/modelhub_submmit_api/outcome_tracker.py @@ -46,6 +46,7 @@ DECISION_RECORD_FIELDS = { "taskType", "submitTime", "lastSyncTime", + "lastOutcomeReconcileAt", "status", "verifyResult", "outcome", @@ -436,16 +437,49 @@ class OutcomeTracker: task_contexts: dict[str, dict[str, Any]] | None = None, ) -> int: try: - begin = self._last_sync_time + # A small overlap tolerates delayed publication and boundary timestamps. + begin = self._last_sync_time - timedelta(hours=24) end = utc_now() # Use fanout for pools to sync outcomes across all accounts list_kwargs: dict[str, Any] = {"begin_time": begin, "end_time": end, "page_size": 100, "only_mine": True} if isinstance(client, ModelHubClientPool): list_kwargs["_fanout_all"] = True - tasks = client.list_tasks(**list_kwargs) - except Exception: + list_kwargs["_strict"] = True + tasks = list(client.list_tasks(**list_kwargs)) + except Exception as exc: + print(f"[outcome-sync] status=deferred reason=history_read_failed error={type(exc).__name__} cursor_advanced=false", flush=True) return 0 + # Time filters are not sufficient to discover old tasks completing late. + # Reconcile a bounded, rotating set of known pending models without a + # time filter. Never infer completion from disappearance alone. + pending_by_model: dict[str, list[dict[str, Any]]] = defaultdict(list) + for record in self._records: + if record.get("outcome") == "pending" and record.get("modelId"): + pending_by_model[str(record["modelId"])].append(record) + floor = datetime.min.replace(tzinfo=end.tzinfo) + def checked_at(rows): + return max((parse_datetime(r.get("lastOutcomeReconcileAt")) or floor for r in rows), default=floor) + eligible = [(model, rows) for model, rows in pending_by_model.items() + if checked_at(rows) < end - timedelta(minutes=15)] + eligible.sort(key=lambda item: (checked_at(item[1]), item[0])) + reconciled = 0 + for model, rows in eligible[:4]: + kwargs = {"model_id": model, "page_size": 100, "only_mine": True} + if isinstance(client, ModelHubClientPool): + kwargs.update({"_fanout_all": True, "_strict": True}) + for row in rows: + row["lastOutcomeReconcileAt"] = end.isoformat() + reconciled += 1 + try: + wanted = {str(row.get("taskId")) for row in rows} + tasks.extend(task for task in client.list_tasks(**kwargs) + if str(task.get("taskId")) in wanted) + except Exception as exc: + print(f"[outcome-sync] reconciliation=deferred error={type(exc).__name__}", flush=True) + # Overlap and model reconciliation may return the same task more than once. + tasks = list({str(t.get("taskId")): t for t in tasks if t.get("taskId")}.values()) + updated_count = 0 enrichment_candidates: list[dict[str, Any]] = [] for task in tasks: @@ -481,6 +515,11 @@ class OutcomeTracker: updated_count += 1 else: status = str(task.get("status") or "").lower() + # Overlap is for refreshing known tasks, not re-importing old + # terminal rows already folded into a compact checkpoint. + timestamp = parse_datetime(task.get("updateTime")) + if self._checkpoint and timestamp and timestamp < self._last_sync_time: + continue if status in TERMINAL_TASK_STATUSES: record = self._create_record_from_task(task) self._records.append(record) @@ -512,12 +551,14 @@ class OutcomeTracker: enrichment_candidates[:FAILURE_ENRICHMENT_LIMIT] ) - if updated_count or enrichment_attempts: + if updated_count or enrichment_attempts or reconciled: self._last_sync_time = end self._rebuild_failed_index() write_jsonl(self.recent_path, self._recent_records) self.save() + print(f"[outcome-sync] tasks={len(tasks)} updated={updated_count} reconciled_models={reconciled} pending={len(self.pending_records())}", flush=True) + return updated_count def bootstrap_from_history_tasks( diff --git a/modelhub_submmit_api/profile_admission.py b/modelhub_submmit_api/profile_admission.py index e041fa709b..f2489e10a2 100644 --- a/modelhub_submmit_api/profile_admission.py +++ b/modelhub_submmit_api/profile_admission.py @@ -13,29 +13,62 @@ def profile_key(row: dict[str, Any]) -> tuple[str, ...] | None: model_type, str(profile.get("quantizationSignature") or profile.get("quantizationMethod") or "none")) -def filter_profile_batch(candidates, pending, stats, *, limit=2): +def profile_budget(candidate, stats, *, limit=2): + """Expand useful public-evidence routes without requiring local exploration. + + Broad evidence earns modest concurrency, not unlimited profile trust. + Specific negative evidence prevents that expansion. + """ + key = profile_key(candidate) + evidence = (stats.get("encodingCombinationStats") or {}).get("|".join(key or ())) or {} + successes = int(evidence.get("successCount") or 0) + failures = max(0, int(evidence.get("failureCount") or 0) - int(evidence.get("platformFailureCount") or 0)) + if successes >= 3 and successes / max(1, successes + failures) >= 0.5: + return None, "proven_encoding" + profile = candidate.get("preflightMetadata") or {} + family = "|".join((*key[:4], str(profile.get("quantizationMethod") or "none"))) if key else "" + broad = (stats.get("profileCombinationStats") or {}).get(family) or {} + negative = failures > successes or int(broad.get("failureCount") or 0) > int(broad.get("successCount") or 0) + public_strong = (candidate.get("frameworkEvidenceQualified") + and candidate.get("frameworkOfficialConfigValid") + and not candidate.get("frameworkCircuitOpen") + and float(candidate.get("frameworkMarketWilsonLowerBound") or 0) >= 0.60 + and int(candidate.get("frameworkMarketSamples") or 0) >= 300) + if public_strong and not negative: + return max(limit, 4), "strong_public_evidence" + return limit, "limited_profile_evidence" + + +def filter_profile_batch(candidates, pending, stats, *, limit=2, max_selected=None): """Reservations include the whole proposed batch; deferred rows are retryable. - Broad public framework statistics are not proof for a specific encoding. - Exact-encoding successes can lift the cap, provided the observed success - rate remains at least 50%. Missing legacy signatures cannot grant this. + Public evidence can expand the cap modestly; exact-encoding successes can + lift it. Model alternatives are considered only until a route is admitted. + Reservations are made only for the requested batch, not the whole pool. """ counts = Counter(profile_key(row) for row in pending if row.get("outcome") == "pending") selected, deferred = [], [] + selected_models = set() for candidate in candidates: + if max_selected is not None and len(selected) >= max_selected: + break + model = candidate.get("repoId") or candidate.get("modelAddress") + if model and model in selected_models: + continue key = profile_key(candidate) - evidence = (stats.get("encodingCombinationStats") or {}).get("|".join(key or ())) or {} - successes = int(evidence.get("successCount") or 0) - failures = max(0, int(evidence.get("failureCount") or 0) - int(evidence.get("platformFailureCount") or 0)) - proven = successes >= 3 and successes / max(1, successes + failures) >= 0.5 + budget, reason = profile_budget(candidate, stats, limit=limit) + candidate["profileAdmissionBudget"] = budget + candidate["profileAdmissionReason"] = reason # Count legacy records with the same method as well, conservatively. legacy = 0 if key and ":" in key[-1]: legacy = counts.get((*key[:-1], key[-1].split(":", 1)[0]), 0) - if key and not proven and counts[key] + legacy >= limit: + if key and budget is not None and counts[key] + legacy >= budget: deferred.append(candidate) continue selected.append(candidate) + if model: + selected_models.add(model) if key: counts[key] += 1 return selected, deferred diff --git a/modelhub_submmit_api/routing_engine.py b/modelhub_submmit_api/routing_engine.py index 0b26a74a06..920c9ee2c4 100644 --- a/modelhub_submmit_api/routing_engine.py +++ b/modelhub_submmit_api/routing_engine.py @@ -8,6 +8,7 @@ from typing import Any from common import read_json, utc_now, write_json from gpu_strategy import wilson_lower_bound from submission_claims import candidate_key +from profile_admission import profile_key ROUTING_STATE_VERSION = 1 @@ -15,7 +16,7 @@ DEFAULT_ROUTING_STATE_PATH = Path(".modelhub_state/routing_intelligence.json") class SuccessFirstRoutingEngine: - """Deterministic success-first routing; queue speed only breaks close races.""" + """Evidence-shrunk routing retaining alternatives through batch admission.""" def __init__( self, @@ -45,7 +46,7 @@ class SuccessFirstRoutingEngine: } return value - def _evidence(self, candidate: dict[str, Any]) -> tuple[str, int, int, float]: + def _evidence(self, candidate: dict[str, Any]) -> tuple[str, float, float, float]: def observed_total(item: dict[str, Any]) -> int: if "failureCount" in item: return max(0, int(item.get("successCount") or 0) + int(item.get("failureCount") or 0) @@ -70,18 +71,16 @@ class SuccessFirstRoutingEngine: total = observed_total(item) if total: sparse = ("local_profile_size_shrunk", item, total) - if total >= 20: - success = int(item.get("successCount") or 0) - return "local_profile_size", success, total, wilson_lower_bound(success, total) if model_type: key = f"{gpu}|{framework}|{task_type}|{model_type}|{quantization}" item = (self.outcome_stats.get("profileCombinationStats") or {}).get(key) or {} total = observed_total(item) if total and sparse is None: sparse = ("local_profile_shrunk", item, total) - if total >= 40: - success = int(item.get("successCount") or 0) - return "local_profile", success, total, wilson_lower_bound(success, total) + exact = (self.outcome_stats.get("encodingCombinationStats") or {}).get( + "|".join(profile_key(candidate) or ())) or {} + if observed_total(exact): + sparse = ("local_encoding_shrunk", exact, observed_total(exact)) public_samples = max(0, int(candidate.get("frameworkMarketSamples") or 0)) public_rate = candidate.get("frameworkMarketSuccessRate") if public_rate is None: @@ -92,27 +91,26 @@ class SuccessFirstRoutingEngine: local_rate = candidate.get("frameworkLocalSuccessRate") local_success = 0 if local_rate is None else max(0, min(local_samples, round(float(local_rate) * local_samples))) - if local_samples >= 100: - total = local_samples - success = local_success - level = "local_task_gpu_framework" - elif public_samples >= 300: + if public_samples > 0: total = public_samples success = public_success level = "official_task_gpu_framework" - elif public_samples > 0: - total = public_samples - success = public_success - level = "official_low_sample" else: total = 2 success = 1 level = "global_conservative_prior" + if local_samples: + # Public and local populations may overlap. Public evidence is a + # bounded prior, not thousands of additional independent trials. + strength = min(12, total) + success = local_success + strength * success / max(1, total) + total = local_samples + strength + level = "local_task_gpu_framework_shrunk" if sparse is not None: level, item, samples = sparse # Eight prior observations stabilize small groups without hiding # their failures behind an unreachable hard sample threshold. - prior_success = round(8 * success / max(1, total)) + prior_success = 8 * success / max(1, total) success = int(item.get("successCount") or 0) + prior_success total = samples + 8 return level, success, total, wilson_lower_bound(success, total) @@ -125,26 +123,35 @@ class SuccessFirstRoutingEngine: eta = max(0.25, float(raw_eta)) if not math.isfinite(eta) or eta >= 9999: raise ValueError - eta_unknown = False + # total/pages-based backlog estimates are not validated durations. + eta_unknown = not bool(candidate.get("queueEtaValidated")) except (TypeError, ValueError): - eta = 36.0 + eta = None eta_unknown = True - success_band = int(lower / 0.05) - expected = (lower * lower) / eta + mean = success / max(1, total) + platform_failures = max(0, int(candidate.get("frameworkRecentPlatformFailures") or 0)) + recent_total = max(platform_failures, int(candidate.get("frameworkRecentTerminalSamples") or 0)) + health = 1 - platform_failures / (recent_total + 8) + mean *= health + lower *= health + success_band = int(lower / 0.05) # Legacy report field, not a ranking key. + expected = mean / eta if not eta_unknown else None annotated.update( { "routingEvidenceLevel": evidence, "routingSuccesses": success, "routingSamples": total, "routingSuccessLowerBound": lower, + "routingSuccessEstimate": mean, + "routingPlatformHealth": health, "routingSuccessBand": success_band, - "routingEtaHours": eta, + "routingEtaHours": eta if not eta_unknown else None, "routingEtaUnknown": eta_unknown, "routingExpectedSuccessPerHour": expected, "routingCommunityModelSuccesses": max( 0, int(candidate.get("communitySuccessfulGpuCount") or 0) ), - "strategyCategory": "unified_success_first", + "strategyCategory": "evidence_throughput_v2", } ) return annotated @@ -173,30 +180,26 @@ class SuccessFirstRoutingEngine: ) if non_transformers and not transformers_unlocked: routes = non_transformers - best = max(float(item["routingSuccessLowerBound"]) for item in routes) - close = [item for item in routes if best - float(item["routingSuccessLowerBound"]) <= 0.05] - close.sort( - key=lambda item: ( - -int(item["routingSuccessBand"]), - -float(item["routingExpectedSuccessPerHour"]), - -int(item["routingSamples"]), - str(item.get("targetGpu") or ""), - str(item.get("framework") or ""), - ) - ) - selected.append(close[0]) + # Keep alternatives until admission, not just the top route. + selected.extend(routes) - selected.sort( - key=lambda item: ( - -int(item["routingSuccessBand"]), - -float(item["routingExpectedSuccessPerHour"]), - -int(item.get("routingCommunityModelSuccesses") or 0), - -int(item["routingSamples"]), - -int(item.get("downloads") or 0), - str(item.get("repoId") or ""), - ) - ) - return selected + # Continuous quality frontiers, anchored to the best remaining route: + # no fixed 5% bin boundaries. Only validated duration estimates may + # trade off quality within a three-percentage-point frontier. + remaining = sorted(selected, key=lambda item: -item["routingSuccessLowerBound"]) + ordered = [] + while remaining: + best = remaining[0]["routingSuccessLowerBound"] + split = next((i for i, r in enumerate(remaining) + if best - r["routingSuccessLowerBound"] > 0.03), len(remaining)) + front, remaining = remaining[:split], remaining[split:] + if all(not r["routingEtaUnknown"] for r in front): + front.sort(key=lambda r: (-r["routingExpectedSuccessPerHour"], -r["routingSuccessLowerBound"])) + else: + front.sort(key=lambda r: (-r["routingSuccessLowerBound"], -r["routingSuccessEstimate"], + -r["routingCommunityModelSuccesses"], str(r.get("repoId")))) + ordered.extend(front) + return ordered @property def submissions_until_refresh(self) -> int: @@ -212,8 +215,8 @@ class SuccessFirstRoutingEngine: routes[key] = int(routes.get(key) or 0) + 1 self.state["acceptedTotal"] = int(self.state.get("acceptedTotal") or 0) + len(candidates) self.state["acceptedSinceRefresh"] = int(self.state.get("acceptedSinceRefresh") or 0) + len(candidates) - categories = self.state.setdefault("acceptedByCategory", {"unified_success_first": 0}) - categories["unified_success_first"] = int(categories.get("unified_success_first") or 0) + len(candidates) + categories = self.state.setdefault("acceptedByCategory", {}) + categories["evidence_throughput_v2"] = int(categories.get("evidence_throughput_v2") or 0) + len(candidates) self.state["generatedAt"] = utc_now().isoformat() write_json(self.path, self.state) return self.state @@ -221,7 +224,7 @@ class SuccessFirstRoutingEngine: def summary(self) -> dict[str, Any]: return { "enabled": True, - "mode": "unified_success_first", + "mode": "evidence_throughput_v2", "statePath": str(self.path), "acceptedTotal": int(self.state.get("acceptedTotal") or 0), "routeCount": len(self.state.get("acceptedByRoute") or {}), diff --git a/modelhub_submmit_api/state_sync.py b/modelhub_submmit_api/state_sync.py index bd2dabb23b..c7d7511c02 100644 --- a/modelhub_submmit_api/state_sync.py +++ b/modelhub_submmit_api/state_sync.py @@ -37,7 +37,7 @@ DEFAULT_CRASH_RECORDS = 50 STATE_OUTCOME_FIELDS = { "agentVersion", "instanceId", "strategyId", "taskId", "modelId", "targetGpu", "framework", "taskType", "submitTime", - "lastSyncTime", "status", "verifyResult", "outcome", "failReason", + "lastSyncTime", "lastOutcomeReconcileAt", "status", "verifyResult", "outcome", "failReason", "modelProfile", "failureCode", "failureCategory", "failureScope", "failureAction", "failureDeterministic", "failureNeedsLlm", "failureClassificationReason", "failureObservedGpuMemoryGiB", diff --git a/modelhub_submmit_api/version.py b/modelhub_submmit_api/version.py index ca9f027432..953dc031b2 100644 --- a/modelhub_submmit_api/version.py +++ b/modelhub_submmit_api/version.py @@ -1 +1 @@ -AGENT_VERSION = "2026.10.28.1" +AGENT_VERSION = "2026.11.12.1" diff --git a/tests/test_outcome_reconciliation.py b/tests/test_outcome_reconciliation.py new file mode 100644 index 0000000000..655f816bdb --- /dev/null +++ b/tests/test_outcome_reconciliation.py @@ -0,0 +1,118 @@ +import sys +import tempfile +import unittest +from datetime import datetime, timezone +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'modelhub_submmit_api')) +from modelhub_client import ModelHubClient, ModelHubClientPool, ModelHubAPIError +from outcome_tracker import OutcomeTracker +from failure_taxonomy import classify_failure_report + + +class OutcomeReconciliationTests(unittest.TestCase): + def tracker(self, root): + return OutcomeTracker(root / 'outcomes.jsonl', checkpoint_path=root / 'checkpoint.json', + recent_path=root / 'recent.jsonl') + + def test_history_ignores_false_last_page_and_deduplicates(self): + client = ModelHubClient(token='test') + rows = {1: [{'taskId': 'a'}], 2: [{'taskId': 'a'}, {'taskId': 'b'}], 3: []} + client.list_tasks_page = lambda **kw: {'data': {'pages': 1, 'total': 1, 'records': rows[kw['current']]}} + self.assertEqual(['a', 'b'], [r['taskId'] for r in client.list_tasks()]) + + def test_history_repeated_page_fails(self): + client = ModelHubClient(token='test') + client.list_tasks_page = lambda **kw: {'data': {'records': [{'taskId': 'a'}]}} + with self.assertRaises(ModelHubAPIError): + client.list_tasks() + + def test_explicit_record_budget_still_works(self): + client = ModelHubClient(token='test') + client.list_tasks_page = lambda **kw: {'data': {'records': [{'taskId': 'a'}, {'taskId': 'b'}]}} + self.assertEqual([{'taskId': 'a'}], client.list_tasks(max_records=1)) + + def test_partial_account_read_does_not_advance_cursor(self): + with tempfile.TemporaryDirectory() as tmp: + tracker = self.tracker(Path(tmp)) + before = tracker._last_sync_time + good, bad = ModelHubClient(token='good'), ModelHubClient(token='bad') + good.list_tasks = lambda **kw: [{'taskId': 'done', 'status': 'failed'}] + def fail(**kw): + raise ModelHubAPIError('read failed') + bad.list_tasks = fail + pool = ModelHubClientPool([good, bad]) + self.assertEqual(0, tracker.sync_from_api(pool)) + self.assertEqual(before, tracker._last_sync_time) + self.assertEqual([], tracker._records) + + def test_old_pending_result_reconciles_without_time_filter_and_retains_version(self): + with tempfile.TemporaryDirectory() as tmp: + tracker = self.tracker(Path(tmp)) + tracker.record_submission('owner/model', 'gpu', 'vllm', 'text-generation', 'old-task', + '2026-01-01T00:00:00Z') + version = tracker._by_task_id['old-task'].get('agentVersion') + client = ModelHubClient(token='test') + calls = [] + def history(**kw): + calls.append(kw) + if kw.get('model_id'): + return [{'taskId': 'old-task', 'modelId': 'owner/model', 'gpuType': 'gpu', + 'status': 'success', 'verifyResult': 1}, + {'taskId': 'unrelated-old-task', 'status': 'failed'}] + return [] + client.list_tasks = history + tracker.sync_from_api(client) + row = tracker._by_task_id['old-task'] + self.assertEqual('success', row['outcome']) + self.assertEqual(version, row.get('agentVersion')) + self.assertNotIn('unrelated-old-task', tracker._by_task_id) + self.assertNotIn('begin_time', calls[-1]) + tracker.sync_from_api(client) + self.assertEqual(1, tracker.get_stats_report()['totals']['successCount']) + + def test_reconciliation_rotates_and_survives_restart(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + tracker = self.tracker(root) + for i in range(6): + tracker.record_submission(f'owner/model{i}', 'gpu', 'vllm', 'text-generation', str(i), + datetime.now(timezone.utc).isoformat()) + client = ModelHubClient(token='test') + models = [] + def history(**kw): + if kw.get('model_id'): + models.append(kw['model_id']) + return [] + client.list_tasks = history + tracker.sync_from_api(client) + self.assertEqual(4, len(models)) + tracker = self.tracker(root) + tracker.sync_from_api(client) + self.assertEqual(6, len(set(models))) + self.assertEqual(6, len(tracker.pending_records())) # Missing is not completed. + + def test_missing_host_runtime_is_not_model_incompatibility(self): + result = classify_failure_report('EXECUTE_EMPTY_RESULT', [ + 'fork/exec /usr/bin/musa/mthreads-container-runtime: no such file or directory']) + self.assertEqual('platform_infrastructure', result.category) + self.assertFalse(result.needs_llm) + + def test_overlap_does_not_reimport_compacted_old_terminal(self): + with tempfile.TemporaryDirectory() as tmp: + tracker = self.tracker(Path(tmp)) + tracker._checkpoint = {'version': 1, 'report': {}} + client = ModelHubClient(token='test') + client.list_tasks = lambda **kw: [{'taskId': 'old', 'status': 'success', + 'verifyResult': 1, 'updateTime': '2020-01-01 00:00:00'}] + tracker.sync_from_api(client) + self.assertNotIn('old', tracker._by_task_id) + + def test_state_sync_retains_reconciliation_marker(self): + from state_sync import STATE_OUTCOME_FIELDS + self.assertIn('lastOutcomeReconcileAt', STATE_OUTCOME_FIELDS) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_throughput_routing.py b/tests/test_throughput_routing.py new file mode 100644 index 0000000000..b466e89e42 --- /dev/null +++ b/tests/test_throughput_routing.py @@ -0,0 +1,93 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'modelhub_submmit_api')) +from routing_engine import SuccessFirstRoutingEngine +from profile_admission import filter_profile_batch, profile_key + + +def route(model='m', gpu='a', rate=0.8): + return dict(repoId=model, targetGpu=gpu, framework='vllm', taskType='text-generation', + frameworkMarketSamples=1000, frameworkMarketSuccessRate=rate, + frameworkMarketWilsonLowerBound=rate - 0.04, + frameworkEvidenceQualified=True, frameworkOfficialConfigValid=True, + preflightMetadata={'modelType': 'qwen', 'quantizationSignature': 'none:abc'}) + + +class ThroughputRoutingTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.engine = SuccessFirstRoutingEngine(Path(self.tmp.name) / 'routing.json') + + def test_alternative_survives_saturated_preferred_profile(self): + best, fallback = route(gpu='a', rate=.9), route(gpu='b', rate=.8) + ordered = self.engine.order_candidates([best, fallback]) + self.assertEqual(2, len(ordered)) + pending = [{**best, 'outcome': 'pending'} for _ in range(4)] + selected, deferred = filter_profile_batch(ordered, pending, {}, max_selected=1) + self.assertEqual(['b'], [r['targetGpu'] for r in selected]) + self.assertEqual(['a'], [r['targetGpu'] for r in deferred]) + + def test_batch_has_one_route_per_model(self): + selected, _ = filter_profile_batch([route(gpu='a'), route(gpu='b'), route('other')], [], {}) + self.assertEqual(['m', 'other'], [r['repoId'] for r in selected]) + + def test_strong_public_evidence_increases_productive_concurrency(self): + candidates = [route(str(i)) for i in range(8)] + self.assertEqual(4, len(filter_profile_batch(candidates, [], {})[0])) + for r in candidates: + r['frameworkEvidenceQualified'] = False + self.assertEqual(2, len(filter_profile_batch(candidates, [], {})[0])) + + def test_exact_failures_prevent_public_expansion_and_lower_ranking(self): + candidate = route() + stats = {'encodingCombinationStats': {'|'.join(profile_key(candidate)): { + 'successCount': 0, 'failureCount': 5}}} + self.assertEqual(2, len(filter_profile_batch([route(str(i)) for i in range(8)], [], stats)[0])) + before = self.engine.annotate(candidate)['routingSuccessLowerBound'] + self.engine.outcome_stats = stats + after = self.engine.annotate(candidate) + self.assertLess(after['routingSuccessLowerBound'], before) + self.assertEqual('local_encoding_shrunk', after['routingEvidenceLevel']) + + def test_small_batch_does_not_consume_unselected_profile_budget(self): + selected, deferred = filter_profile_batch([route(str(i)) for i in range(8)], [], {}, max_selected=1) + self.assertEqual(1, len(selected)) + self.assertEqual([], deferred) + + def test_unknown_queue_does_not_invent_eta_or_success_per_hour(self): + result = self.engine.annotate({**route(), 'queueBacklogHours': .01}) + self.assertTrue(result['routingEtaUnknown']) + self.assertIsNone(result['routingExpectedSuccessPerHour']) + + def test_validated_speed_can_win_within_quality_frontier(self): + slow = {**route('slow', rate=.90), 'queueBacklogHours': 100, 'queueEtaValidated': True} + fast = {**route('fast', rate=.89), 'queueBacklogHours': 1, 'queueEtaValidated': True} + self.assertEqual('fast', self.engine.order_candidates([slow, fast])[0]['repoId']) + poor = {**route('poor', rate=.3), 'queueBacklogHours': .25, 'queueEtaValidated': True} + self.assertEqual('slow', self.engine.order_candidates([poor, slow])[0]['repoId']) + + def test_sample_threshold_has_no_abrupt_source_switch(self): + a = {**route(), 'frameworkLocalSamples': 99, 'frameworkLocalSuccessRate': .3} + b = {**a, 'frameworkLocalSamples': 100} + self.assertLess(abs(self.engine._evidence(a)[3] - self.engine._evidence(b)[3]), .01) + + def test_platform_failures_lower_operational_score(self): + healthy = self.engine.annotate(route()) + unhealthy = self.engine.annotate({**route(), 'frameworkRecentPlatformFailures': 8, + 'frameworkRecentTerminalSamples': 10}) + self.assertLess(unhealthy['routingSuccessEstimate'], healthy['routingSuccessEstimate']) + + def test_readmission_after_pending_completes(self): + candidate = route() + pending = [{**candidate, 'outcome': 'pending'} for _ in range(4)] + self.assertEqual([], filter_profile_batch([candidate], pending, {})[0]) + pending[0]['outcome'] = 'success' + self.assertEqual(1, len(filter_profile_batch([candidate], pending, {})[0])) + + +if __name__ == '__main__': + unittest.main()