Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 29 additions & 16 deletions loopx/control_plane/collaboration/steward_managed_mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {readTurnSelectionRejection} from "../turn_driver/selection_rejection.ts"
import {EffectiveAction} from "../quota/effective_action.generated.ts";
import {projectTurnBoundary, turnPlanWorkSource} from "../quota/turn_envelope.ts";
import {projectGoalCreationExecutionRequest} from "../goals/creation_execution.ts";
import {parseTodoTimestampMicros} from "../runtime_timestamp.ts";

/** A stopped observation may get a new Chat carrier for the same native
* identity. After a recovery starts, only another proven process restart or a
Expand Down Expand Up @@ -1122,11 +1123,24 @@ function hasMatchingApprovedReviewerDeclaration(item: JsonObject, requiredTokens
);
}

function classifyStalledBucket(stalledAgeMs: number, authorReplyBypass: boolean): string {
const MICROS_PER_HOUR = 3_600_000_000n;

function stalledAgeThresholdMicros(hours: number): bigint {
const [mantissa, exponent = "0"] = hours.toString().split("e");
const [whole, fraction = ""] = mantissa.split(".");
const shift = Number(exponent) - fraction.length;
const micros = BigInt(whole + fraction) * MICROS_PER_HOUR;
if (shift >= 0) return micros * 10n ** BigInt(shift);
const divisor = 10n ** BigInt(-shift);
// Ages are integral microseconds, so a fractional cutoff must round up.
return (micros + divisor - 1n) / divisor;
}

function classifyStalledBucket(stalledAgeMicros: bigint, authorReplyBypass: boolean): string {
if (authorReplyBypass) return "awaiting_maintainer_reply";
if (stalledAgeMs >= 168 * 3_600_000) return "7d_plus";
if (stalledAgeMs >= 72 * 3_600_000) return "72h_plus";
if (stalledAgeMs >= 24 * 3_600_000) return "24h_to_72h";
if (stalledAgeMicros >= 168n * MICROS_PER_HOUR) return "7d_plus";
if (stalledAgeMicros >= 72n * MICROS_PER_HOUR) return "72h_plus";
if (stalledAgeMicros >= 24n * MICROS_PER_HOUR) return "24h_to_72h";
return "under_24h";
}

Expand All @@ -1135,13 +1149,12 @@ function filterScopedRepositoryItems(
filter: JsonObject | null,
observedAtValue: unknown,
): { items: JsonObject[]; observationIncomplete: boolean } {
const minStalledHours = typeof filter?.min_stalled_hours === "number" ? filter.min_stalled_hours : null;
let observedAtMs = NaN;
if (minStalledHours !== null) {
observedAtMs = typeof observedAtValue === "string" ? Date.parse(observedAtValue) : NaN;
if (!Number.isFinite(observedAtMs)) {
throw new EffectRuntimeRequestError("scoped monitor min_stalled_hours requires a valid observed_at timestamp");
}
const thresholdMicros = typeof filter?.min_stalled_hours === "number"
? stalledAgeThresholdMicros(filter.min_stalled_hours) : null;
const observedAtMicros = thresholdMicros !== null && typeof observedAtValue === "string"
? parseTodoTimestampMicros(observedAtValue.trim()) : null;
if (thresholdMicros !== null && observedAtMicros === null) {
throw new EffectRuntimeRequestError("scoped monitor min_stalled_hours requires a valid observed_at timestamp");
}
const effectiveVerdicts = Array.isArray(filter?.effective_verdicts)
? new Set(filter.effective_verdicts.map(String))
Expand Down Expand Up @@ -1176,7 +1189,7 @@ function filterScopedRepositoryItems(
if (authorMode === "include" && (!login || !authors.has(login))) continue;
if (authorMode === "exclude" && login && authors.has(login)) continue;
}
if (minStalledHours !== null) {
if (thresholdMicros !== null && observedAtMicros !== null) {
const authorReplied = item.author_replied_after_request_changes === true
|| reviewSummary?.author_replied_after_request_changes === true;
const hasExplicitStalledSince = Object.prototype.hasOwnProperty.call(item, "stalled_since")
Expand All @@ -1201,17 +1214,17 @@ function filterScopedRepositoryItems(
return { items: [], observationIncomplete: true };
}
const basisIso = rawStalledSince ?? (typeof item.updatedAt === "string" ? item.updatedAt : null);
const basisMs = basisIso !== null ? Date.parse(basisIso) : NaN;
const basisMicros = basisIso === null ? null : parseTodoTimestampMicros(basisIso.trim());
const stalledAgeMicros = basisMicros === null ? null : observedAtMicros - basisMicros;
const authorReplyBypass = authorReplied && authorMode === "exclude";
const thresholdMet = Number.isFinite(basisMs) && observedAtMs - basisMs >= minStalledHours * 3_600_000;
const thresholdMet = stalledAgeMicros !== null && stalledAgeMicros >= thresholdMicros;
if (!authorReplyBypass && !thresholdMet) {
continue;
}
const stalledAgeMs = Number.isFinite(basisMs) ? Math.max(0, observedAtMs - basisMs) : 0;
matched.push({
...item,
stalled_threshold_met: thresholdMet,
stalled_bucket: classifyStalledBucket(stalledAgeMs, authorReplyBypass),
stalled_bucket: classifyStalledBucket(stalledAgeMicros ?? 0n, authorReplyBypass),
});
} else {
matched.push(item);
Expand Down
67 changes: 67 additions & 0 deletions regression/StewardStalledAgePrecision.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import Std

/-
Run with Lean 4.22.0: `lean -DwarningAsError=true regression/StewardStalledAgePrecision.lean`.

The model starts with parsed UTC timestamps and a positive rational cutoff
expressed in microseconds from the configured decimal hours. The runtime
regression covers the timestamp parser, decimal conversion, and actual
scoped observation and material buckets.
-/

namespace StewardStalledAgePrecision

def cutoffMicros (numerator denominator : Int) : Int :=
(numerator + denominator - 1) / denominator

theorem integral_age_matches_fractional_cutoff
(age numerator denominator : Int) (positive : 0 < denominator) :
cutoffMicros numerator denominator ≤ age ↔ numerator ≤ age * denominator := by
unfold cutoffMicros
rw [Int.ediv_le_iff_le_mul positive]
omega

def includeItem (hasCoverage inScope authorReply : Bool) (age cutoff : Int) : Bool :=
hasCoverage && inScope && (authorReply || decide (cutoff ≤ age))

theorem early_age_without_reply_is_excluded (age cutoff : Int) (early : age < cutoff) :
includeItem true true false age cutoff = false := by
have below : ¬cutoff ≤ age := by omega
simp [includeItem, below]

theorem author_reply_still_requires_coverage_and_scope
(hasCoverage inScope : Bool) (age cutoff : Int) :
includeItem hasCoverage inScope true age cutoff = (hasCoverage && inScope) := by
simp [includeItem]

inductive Bucket where
| under24 | from24 | from72 | from168
deriving DecidableEq

def bucket (age : Int) : Bucket :=
if age ≥ 604800000000 then .from168
else if age ≥ 259200000000 then .from72
else if age ≥ 86400000000 then .from24
else .under24

theorem bucket_changes_at_each_exact_boundary :
bucket (86400000000 - 1) = .under24 ∧ bucket 86400000000 = .from24 ∧
bucket (259200000000 - 1) = .from24 ∧ bucket 259200000000 = .from72 ∧
bucket (604800000000 - 1) = .from72 ∧ bucket 604800000000 = .from168 := by
simp [bucket]

-- The retained anchor is one microsecond after a whole second.
theorem old_milliseconds_could_promote_the_bucket :
let anchor : Int := 1
let observed : Int := 86400000000
bucket ((observed / 1000 - anchor / 1000) * 1000) = .from24 ∧
bucket (observed - anchor) = .under24 := by
simp [bucket]

#print axioms integral_age_matches_fractional_cutoff
#print axioms early_age_without_reply_is_excluded
#print axioms author_reply_still_requires_coverage_and_scope
#print axioms bucket_changes_at_each_exact_boundary
#print axioms old_milliseconds_could_promote_the_bucket

end StewardStalledAgePrecision
36 changes: 36 additions & 0 deletions tests/control_plane_ts/steward_managed_mode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,42 @@ test("observeStewardSignalMonitor uses stalled_since, author-reply bypass, and s
assert.equal(at24hFromSixHour.scoped_repository_items[0].stalled_bucket, "24h_to_72h");
});

test("stalled PR eligibility and buckets retain microsecond boundary precision", () => {
const stalledSince = "2026-11-20T09:00:00.000001Z";
const repository = {status: "ok", repository: "acme/widgets", items: [{
number: 201, title: "Synthetic watch item", isDraft: false, mergeable: "MERGEABLE", author: {login: "alice"},
updatedAt: stalledSince, stalled_since: stalledSince,
review_summary: {effective_verdict: "REQUEST_CHANGES", latest_request_changes_review_id: "PRR_201"},
}]};
const observe = (hours: number, observedAt: string) => observeStewardSignalMonitor({
signal_scope: {
schema_version: "steward_signal_monitor_scope_v0", include_portfolio: false, include_inbox: false,
pr_filter: {
exclude_drafts: true, effective_verdicts: ["REQUEST_CHANGES"],
author_mode: "include", authors: ["alice"], min_stalled_hours: hours,
},
},
repository_snapshot: repository,
observed_at: observedAt,
}).scoped_repository_items;

assert.deepEqual(observe(24, "2026-11-21T09:00:00Z"), []);
assert.equal(observe(24, "2026-11-21T17:00:00.000001+08:00")[0].stalled_bucket, "24h_to_72h");
for (const [date, beforeBucket, exactBucket] of [
["2026-11-21", "under_24h", "24h_to_72h"],
["2026-11-23", "24h_to_72h", "72h_plus"],
["2026-11-27", "72h_plus", "7d_plus"],
] as const) {
assert.equal(observe(6, `${date}T09:00:00Z`)[0].stalled_bucket, beforeBucket);
assert.equal(observe(6, `${date}T09:00:00.000001z`)[0].stalled_bucket, exactBucket);
}
assert.deepEqual(observe(0.1, "2026-11-20T09:06:00Z"), []);
assert.equal(observe(0.1, "2026-11-20T09:06:00.000001Z")[0].stalled_threshold_met, true);
assert.deepEqual(observe(Number.MIN_VALUE, stalledSince), []);
assert.equal(observe(Number.MIN_VALUE, "2026-11-20T09:00:00.000002Z")[0].stalled_threshold_met, true);
assert.deepEqual(observe(Number.MAX_VALUE, "9999-12-31T23:59:59Z"), []);
});

test("observeStewardSignalMonitor fails closed on comments_coverage_incomplete only for matching stalled-age PRs", () => {
const externalStalledScope = {
schema_version: "steward_signal_monitor_scope_v0",
Expand Down
Loading