Download engine/tests/test_app_perimeter.py from s-ttp/crucible: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/spaces/s-ttp/crucible/resolve/main/engine/tests/test_app_perimeter.py
- Command line
-
hf download hf://spaces/s-ttp/crucible/engine/tests/test_app_perimeter.py
-
curl -L -o test_app_perimeter.py https://huggingface.co/spaces/s-ttp/crucible/resolve/main/engine/tests/test_app_perimeter.py
15.5 kB
| """APP perimeter / story-segment remediation (run 575f809df244ef01): the company files ONE reportable segment, the | |
| pipeline asked a model to recall a segment mix, the stale recall ("Software Platform", "Apps") reached the | |
| storytellers, and story_fcff valued a business sold the year before. The canonical CorporateActionState also left the | |
| sale UNVERIFIED although the company's own 10-Q states its completion. | |
| APP-shaped inputs; nothing in the engine names APP or "Apps". | |
| """ | |
| import copy | |
| import os | |
| import sys | |
| import pytest | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| import business as BZ # noqa: E402 | |
| import corporate_actions as CA # noqa: E402 | |
| import pipeline_fixtures as F # noqa: E402 | |
| import predict_yearly as PY # noqa: E402 | |
| import story_dcf as SD # noqa: E402 | |
| SOLD = "Mobile gaming apps business (sold to Tripledot Studios)" | |
| SEG_ID = "app:ReportableSegmentMember" | |
| BASE = {"perimeter": "consolidated", "corporate_action_id": None} | |
| EDGAR_8K = [{"filed": "2025-07-01", "items": ["1.01", "8.01", "9.01"], "kind": "material_agreement", "excerpt": None, | |
| "url": "https://www.sec.gov/Archives/edgar/data/1751008/000175100825000061/app-20250630.htm"}, | |
| {"filed": "2025-05-07", "items": ["1.01", "2.02", "9.01"], "kind": "material_agreement", "excerpt": None, | |
| "url": "https://www.sec.gov/Archives/edgar/data/1751008/000175100825000051/app-20250507.htm"}] | |
| TENQ = {"form": "10-Q", "date": "2025-06-30", "filed": "2025-08-06", | |
| "url": "https://www.sec.gov/Archives/edgar/data/1751008/000175100825000070/app-20250630.htm", | |
| "snippet": "the sale of the Apps Business to Tripledot was completed on June 30, 2025"} | |
| def canon(lines=()): | |
| seg = {"member": SEG_ID, "segment_id": SEG_ID, "name": "Reportable", "revenue": 3.766e9, "revenue_prior": 2.418e9, | |
| "revenue_share": 1.0, "kind": "business_line", "product_lines": list(lines), | |
| "allocations": [{"industry": "Software (System & Application)", "fraction": 1.0, "basis": "company industry"}]} | |
| return {"status": "SINGLE_SEGMENT", "segments": [seg], "consolidated_revenue": 3.766e9, "coverage": 1.0, "excluded_revenue": 0.0, | |
| "source": "SEC 10-Q XBRL (accession 0001751008-26-000059, filed 2026-08-05)", "filed": "2026-08-05", | |
| "period_start": "2026-01-01", "period_end": "2026-06-30", "business_mix_allowed": False, "reason": "reconciled"} | |
| def recall(evidence=TENQ): | |
| a = {"kind": "divestiture", "business": SOLD, "status": "completed", "effective": "2025-06-30"} | |
| if evidence: | |
| a["evidence"] = dict(evidence) | |
| return [a] | |
| def actions(evidence=TENQ): | |
| return CA.build("APP", None, EDGAR_8K, recall(evidence), canon()) | |
| def decomposition(lines=(), evidence=TENQ): | |
| return BZ.build("APP", canon(lines), actions(evidence), BASE) | |
| def fcff_ctx(decomp): | |
| return {"ticker": "APP", "revenue": 6.829e9, "shares": 305.7e6, "price": 305.66, "op_margin": 0.774, "rf": 0.0524, "erp": 0.0409, | |
| "beta": 1.28, "debt": 3.5e9, "cash": 3.1e9, "market_cap": 103.5e9, "stage": "high-growth", "interest_coverage": 100, | |
| "sector": "TECHNOLOGY", "business_decomposition": decomp} | |
| FLAT = {"story": "One continuing advertising platform; margins normalise from today's peak as competition matures.", "tam_at_maturity_usd_b": 450.0, "plausible_peak_share": 0.075, | |
| "years_to_maturity": 10, "target_operating_margin": 0.52, "sales_to_capital": 2.6, "failure_probability": 0.05, "key_risk": "privacy"} | |
| RECALLED = dict(FLAT, segments=[ | |
| {"name": "Software Platform", "tam_at_maturity_usd_b": 450.0, "plausible_peak_share": 0.075, "target_operating_margin": 0.52, "sales_to_capital": 2.6}, | |
| {"name": "Apps", "tam_at_maturity_usd_b": 100.0, "plausible_peak_share": 0.05, "target_operating_margin": 0.18, "sales_to_capital": 1.5}]) | |
| def teller(answers, prompts=None): | |
| it = iter(answers) | |
| def call(system, prompt): | |
| if prompts is not None: | |
| prompts.append(prompt) | |
| return copy.deepcopy(next(it)) | |
| return call | |
| # ── A: a recalled decomposition is not canonical business state ── | |
| def test_A_model_recall_cannot_establish_business_identity(): | |
| d = decomposition() | |
| assert d["source_type"] == BZ.SINGLE_FILED_SEGMENT and d["mode"] == BZ.ONE_BUSINESS | |
| assert [b["business_id"] for b in BZ.eligible(d)] == [SEG_ID] | |
| codes = {c for c, _m in BZ.check_segments(RECALLED["segments"], d)} | |
| assert BZ.IDENTITY in codes and BZ.DISPOSED in codes # "Software Platform" is not of record; "Apps" left | |
| # the recalled-brief fallback is gone, and a one-segment filer gets no segment brief at all | |
| assert not hasattr(PY, "_segment_economics_brief") and PY._product_line_brief(d) is None | |
| # a decomposition that came from model recall is refused by the state check | |
| forged = dict(d, source_type=BZ.MODEL_RECALL) | |
| assert any(c == BZ.SOURCE for c, _m in BZ.check_state(forged, actions(), [])) | |
| txt = BZ.prompt_block(d) | |
| assert "ONE BUSINESS" in txt and 'leave "segments" empty' in txt and "NO LONGER PART OF THE COMPANY" in txt and SOLD in txt | |
| # ── B: a completed disposal cannot be reintroduced by a storyteller ── | |
| def test_B_a_disposed_business_in_the_story_fails(): | |
| d = decomposition() | |
| sold = next(b for b in d["businesses"] if not b["continuing_operations"]) | |
| assert sold["corporate_action_id"] == "APP-DIVESTITURE-apps-gaming" and not sold["story_eligible"] | |
| assert any(c == BZ.DISPOSED for c, _m in BZ.check_segments([{"name": "Apps"}], d)) | |
| assert any(c == BZ.DISPOSED for c, _m in BZ.check_segments([{"business_id": sold["business_id"]}], d)) | |
| # story_fcff's precondition: the build is rejected, never trimmed and continued | |
| assert SD.story_fcff(fcff_ctx(d), copy.deepcopy(RECALLED)) is None and "not eligible businesses" in SD.reason() | |
| # the storyteller is asked once more with the valid list; a second invalid answer is rejected | |
| prompts = [] | |
| A, out = SD._story_once(fcff_ctx(d), teller([RECALLED, FLAT, FLAT], prompts)) # + the margin 3P question, once | |
| assert out is not None and not A.get("segments") and "NOT ELIGIBLE" in prompts[-1] and BZ.DISPOSED in prompts[-1] | |
| assert out["assumptions"]["segments"] is None and out["assumptions"]["revenue_N_usd_b"] == 33.75 | |
| A, out = SD._story_once(fcff_ctx(d), teller([RECALLED, RECALLED, RECALLED])) | |
| assert A is None and out is None and "(twice)" in SD.reason() | |
| # and a state that carries such a story fails the forecast stage | |
| data = F.all_data() | |
| data.update(segments_canonical=canon(), corp_actions=recall(), edgar_actions=EDGAR_8K) | |
| st = F.story(); st["assumptions"]["segments"] = [{"name": "Software Platform", "rev_usd_b": 33.75, "margin": 0.52, "sales_to_capital": 2.6}, | |
| {"name": "Apps", "rev_usd_b": 5.0, "margin": 0.18, "sales_to_capital": 1.5}] | |
| run, payload, failed = F.run_pipeline(data=data, forecast_over={"story": F.story_invariants(st)}) | |
| ids = {c.id: c for v in run.validations for c in v.checks} | |
| assert failed == "FORECAST" and payload is None | |
| assert ids["DISPOSED_BUSINESS_EXCLUSION"].status == "FAIL" and ids["STORY_BUSINESS_IDENTITY"].status == "FAIL" | |
| # ── C: a story segment must be on the story base's perimeter ── | |
| def test_C_a_non_continuing_business_fails_the_perimeter_check(): | |
| # the filing before the sale: two reportable segments, one of them the business separated inside the trailing window | |
| two = {"status": "RECONCILED", "source": "SEC 10-Q XBRL", "filed": "2025-05-07", "period_end": "2025-03-31", | |
| "segments": [{"segment_id": "app:SoftwarePlatformMember", "name": "Software Platform", "revenue": 1.159e9, "kind": "business_line"}, | |
| {"segment_id": "app:AppsMember", "name": "Apps", "revenue": 0.325e9, "kind": "business_line"}]} | |
| base = {"perimeter": "continuing company", "corporate_action_id": "APP-DIVESTITURE-apps-gaming"} | |
| act = CA.build("APP", None, EDGAR_8K, recall(), two) | |
| d = BZ.build("APP", two, act, base, excluded_segment_ids=["app:AppsMember"]) | |
| assert d["perimeter_id"] == "continuing company:APP-DIVESTITURE-apps-gaming" | |
| assert [b["business_id"] for b in BZ.eligible(d)] == ["app:SoftwarePlatformMember"] and d["mode"] == BZ.ONE_BUSINESS | |
| bad = BZ.check_segments([{"business_id": "app:SoftwarePlatformMember"}, {"business_id": "app:AppsMember"}], d) | |
| assert {c for c, _m in bad} == {BZ.PERIMETER, BZ.DISPOSED} | |
| assert BZ.check_segments([{"business_id": "app:SoftwarePlatformMember"}], d) == [] | |
| # ── D: the issuer's own 10-Q verifies a completion without an 8-K Item 2.01 ── | |
| def test_D_a_10q_completion_sentence_completes_the_action(): | |
| a = actions()["actions"][0] | |
| assert a["status"] == CA.COMPLETED and a["completed_date"] == "2025-06-30" and a["persona_evidence_allowed"] | |
| assert a["status_source"] == "SEC 10-Q filed 2025-08-06" and a["evidence"][-1]["form"] == "10-Q" | |
| assert a["perimeter_effect"] == CA.DISPOSAL_EFFECT and a["action_id"] == "APP-DIVESTITURE-apps-gaming" | |
| assert CA.check(actions()) == [] | |
| # recall alone, a sentence that does not name the business, or one that only expects a closing: still UNVERIFIED | |
| for ev in (None, dict(TENQ, snippet="the transaction was completed on June 30, 2025"), | |
| dict(TENQ, snippet="the sale to Tripledot is expected to be completed in the second quarter"), | |
| dict(TENQ, form="press release"), dict(TENQ, url="https://example.com/a.htm")): | |
| assert actions(ev)["actions"][0]["status"] == CA.UNVERIFIED, ev | |
| # completion evidence the pipeline found but the canonical state dropped is a lineage failure | |
| raw = [{"business": SOLD, "kind": "divestiture", "state": "completed", "completed": "2025-06-30", | |
| "source": "10-Q filed 2025-06-30", "state_basis": "SEC filing"}] | |
| lost = actions(None) | |
| assert any(c == "CORPORATE_ACTION_COMPLETION_LINEAGE" for c, _m in BZ.check_state(BZ.build("APP", canon(), lost, BASE), lost, raw)) | |
| assert BZ.check_state(decomposition(), actions(), raw) == [] | |
| # ── E: a one-segment issuer is valued as one business ── | |
| def test_E_one_business_story_is_valid_and_publishes(): | |
| d = decomposition() | |
| assert BZ.check_segments([], d) == [] and BZ.check_segments(None, d) == [] | |
| prompts = [] | |
| A, out = SD._story_once(fcff_ctx(d), teller([FLAT, FLAT], prompts)) | |
| # no segment build was asked for: the only follow-up is the margin 3P question, put once whatever the story says | |
| assert out is not None and out["assumptions"]["segments"] is None and len(prompts) == 2 | |
| assert "ONE BUSINESS" in prompts[0] and not any("SEGMENT BUILD REQUIRED" in p for p in prompts) | |
| assert "target operating margin" in prompts[1] | |
| # the single business may be named by its own id; any second business is refused | |
| one = dict(FLAT, segments=[{"business_id": SEG_ID, "tam_at_maturity_usd_b": 450.0, "plausible_peak_share": 0.075, | |
| "target_operating_margin": 0.52, "sales_to_capital": 2.6}]) | |
| assert SD.story_fcff(fcff_ctx(d), copy.deepcopy(one)) is not None | |
| data = F.all_data() | |
| data.update(segments_canonical=canon(), corp_actions=recall(), edgar_actions=EDGAR_8K) | |
| run, payload, failed = F.run_pipeline(data=data) | |
| assert failed is None, [(c.id, c.detail) for v in run.validations for c in v.blocking] | |
| ids = {c.id: c for v in run.validations for c in v.checks} | |
| for cid in ("STORY_BUSINESS_IDENTITY", "STORY_SEGMENT_PERIMETER", "DISPOSED_BUSINESS_EXCLUSION", "STORY_BUSINESS_SOURCE", | |
| "CORPORATE_ACTION_COMPLETION_LINEAGE"): | |
| assert ids[cid].status == "PASS", (cid, ids[cid].detail) | |
| bd = run.state.valuation.get("business_decomposition") | |
| assert bd["mode"] == BZ.ONE_BUSINESS and [b["business_id"] for b in BZ.eligible(bd)] == [SEG_ID] | |
| assert run.state.corporate_actions.get("state")["actions"][0]["status"] == CA.COMPLETED | |
| assert "**Segment build**" not in payload["markdown"] | |
| # ── F: a finer decomposition the company itself files may be used ── | |
| def test_F_filed_product_lines_are_an_eligible_decomposition(): | |
| lines = [{"name": "Advertising", "revenue": 3.0e9, "member": "app:AdvertisingMember"}, {"name": "Subscriptions", "revenue": 0.766e9}] | |
| d = decomposition(lines) | |
| assert d["source_type"] == BZ.FILED_PRODUCT_LINES and d["mode"] == BZ.MULTI_BUSINESS | |
| ids = [b["business_id"] for b in BZ.eligible(d)] | |
| assert ids == ["app:AdvertisingMember", f"{SEG_ID}#subscriptions"] | |
| assert all(b["source_type"] == BZ.FILED_PRODUCT_LINES and b["perimeter_id"] == d["perimeter_id"] and b["source"] for b in BZ.eligible(d)) | |
| assert BZ.check_state(d, actions(), []) == [] | |
| brief = PY._product_line_brief(d) | |
| assert brief["filed"] and [g["segment_id"] for g in brief["segments"]] == ids | |
| segs = dict(FLAT, segments=[ | |
| {"business_id": ids[0], "tam_at_maturity_usd_b": 400.0, "plausible_peak_share": 0.075, "target_operating_margin": 0.55, "sales_to_capital": 2.6}, | |
| {"business_id": ids[1], "tam_at_maturity_usd_b": 60.0, "plausible_peak_share": 0.06, "target_operating_margin": 0.30, "sales_to_capital": 2.0}]) | |
| out = SD.story_fcff(fcff_ctx(d), copy.deepcopy(segs)) | |
| rows = out["assumptions"]["segments"] | |
| assert [r["business_id"] for r in rows] == ids and [r["name"] for r in rows] == ["Advertising", "Subscriptions"] | |
| assert all(r["perimeter_id"] == d["perimeter_id"] for r in rows) | |
| assert 'business_id "app:AdvertisingMember" = Advertising' in BZ.prompt_block(d) | |
| # lines that do not sum to the segment are not a decomposition; a disposed business is still never eligible | |
| assert decomposition([{"name": "Advertising", "revenue": 1.0e9}, {"name": "Subscriptions", "revenue": 0.5e9}])["mode"] == BZ.ONE_BUSINESS | |
| assert any(c == BZ.DISPOSED for c, _m in BZ.check_segments(segs["segments"] + [{"name": "Apps"}], d)) | |
| def test_a_segment_build_with_near_term_growth_reconciles_to_the_paths_revenue(): | |
| """ABT, DUK, ON 2026-11-25: with near-term inputs revenue at maturity is the growth path's outcome, and the segments | |
| are its split in their market size × share proportions (SEGMENT_BUILD_RECONCILES withheld all three).""" | |
| lines = [{"name": "Advertising", "revenue": 3.0e9, "member": "app:AdvertisingMember"}, {"name": "Subscriptions", "revenue": 0.766e9}] | |
| d = decomposition(lines) | |
| ids = [b["business_id"] for b in BZ.eligible(d)] | |
| segs = dict(FLAT, revenue_growth_next_year=0.20, revenue_cagr_years_2_5=0.15, segments=[ | |
| {"business_id": ids[0], "tam_at_maturity_usd_b": 400.0, "plausible_peak_share": 0.075, "target_operating_margin": 0.55, "sales_to_capital": 2.6}, | |
| {"business_id": ids[1], "tam_at_maturity_usd_b": 60.0, "plausible_peak_share": 0.06, "target_operating_margin": 0.30, "sales_to_capital": 2.0}]) | |
| out = SD.story_fcff(fcff_ctx(d), copy.deepcopy(segs)) | |
| a, rows = out["assumptions"], out["assumptions"]["segments"] | |
| assert sum(r["rev_usd_b"] for r in rows) == pytest.approx(a["revenue_N_usd_b"], rel=1e-3) | |
| assert rows[0]["rev_usd_b"] / rows[1]["rev_usd_b"] == pytest.approx((400 * 0.075) / (60 * 0.06), rel=1e-9) | |
| assert rows[0]["rev_usd_b_tam_share"] == pytest.approx(30.0) and rows[0]["implied_share"] == pytest.approx(rows[0]["rev_usd_b"] / 400) | |