Skip to content
All articles
BLOG

Finite Hypothesis Spaces: How to Safely Generate Paywalls with LLMs

Use finite native component contracts, structured generation, semantic validation, and bandit evaluation to keep LLM-generated paywall variations safe.

Key Takeaways

  • Safe generative paywalls use an LLM to propose values inside a finite, human-approved component and offer space—not to generate production executable code.
  • Structured Outputs and schemas constrain shape, not semantic truth; validators must also check product relationships, claims, localization, accessibility, and policy constraints.
  • ONLang’s pattern is “the LLM proposes offline, the validator gates, a person approves, the optimizer evaluates,” with native rendering and existing StoreKit or Play Billing unchanged.

An LLM can produce a hundred paywall headlines in seconds. That is useful only if the production system can reject the ones that invent features, misstate a trial, exceed layout limits, or manipulate users. The core design problem is not generation speed. It is converting an open-ended model into a bounded contributor to a controlled experiment.

A finite hypothesis space defines every dimension the system may vary: approved components, enumerated layouts, bounded copy tokens, valid product combinations, and fixed actions. Everything outside that space remains application code or human-reviewed configuration.

Why unbounded code generation does not belong in checkout

Generating Swift, Kotlin, or JavaScript for immediate execution makes the model part of the app’s trusted computing base. A plausible snippet can reference unavailable APIs, bypass entitlement logic, break accessibility, or introduce behavior that was never reviewed. Store policies and security boundaries also restrict downloaded executable behavior.

Even generating an unrestricted UI document creates too many degrees of freedom. Arbitrary nesting can hide disclosures, arbitrary styles can make text unreadable, and arbitrary actions can turn a harmless copy experiment into a purchase-flow change. A screenshot cannot validate all states.

Finite contracts reverse the control flow. Engineers implement and test native components. Product and legal reviewers approve the allowed dimensions. The model proposes a candidate assignment. A deterministic validator accepts or rejects it. Only valid candidates become experiment arms.

This is ONLang’s core manifesto: contracts, not code. The LLM proposes, the validator gates, a person approves, and the optimizer decides. ONLang’s planner runs offline, never in the request path; it never writes tap actions, and nothing it drafts reaches a device without passing the compiler and a human reviewer. Native UIKit, SwiftUI, Jetpack Compose, or React Native components remain in the binary.

Define a finite registry

Start with semantic components rather than generic visual primitives. A PaywallIntro can own accessible heading behavior. A PlanToggle can enforce exactly two valid products and a selected default. A PurchaseButton can emit only the purchase action. No component accepts arbitrary code or class names.

{
  "registry": "acme_fitness",
  "version": "1.0.0",
  "products": ["annual", "monthly"],
  "components": {
    "PaywallIntro": {
      "props": {
        "headline": { "type": "token", "max_chars": 40 },
        "body": { "type": "token", "max_chars": 90 }
      }
    },
    "PlanToggle": {
      "props": {
        "products": { "type": "products", "min_items": 2, "max_items": 2 },
        "default": { "type": "product" }
      },
      "interactive": true,
      "emits": ["select"]
    },
    "PurchaseButton": {
      "props": {
        "title": { "type": "token", "max_chars": 28 }
      }
    }
  }
}

The registry bounds text and product structure, but human policy must define which tokens are allowed to vary. Auto-renewal terms, privacy links, cancellation language, and restore labels may be mandatory fixed content rather than hypotheses. Product identifiers and purchase actions should not be model-generated at all.

Document each allowed dimension with a rationale. “Headline can emphasize plan personalization” is safer than “make the paywall more persuasive.” The rationale helps reviewers recognize manipulative or false proposals before metrics reward them.

Use structured generation as the first gate

Modern LLM APIs can enforce a JSON schema or structured output shape. That reduces malformed responses and parsing failures. It does not ensure that a headline is truthful, that a trial duration matches the store, or that the selected plan is appropriate for a region.

A generation request should include the allowed keys, current product facts, locale, approved value propositions, prohibited claims, and the experiment rationale. Ask for a candidate, not a complete application. Reject extra keys rather than merging them into a release.

import { z } from "zod";

const Hypothesis = z
  .object({
    id: z.string().regex(/^[a-z0-9.-]+$/),
    rationale: z.string().min(10).max(240),
    assignments: z
      .object({
        "intro.headline": z.string().min(1).max(40),
        "cta.title": z.string().min(1).max(28),
      })
      .strict(),
  })
  .strict();

const prohibited = /guaranteed|forever free|cancel anytime|no risk/i;

export function validateHypothesis(input: unknown, approvedFeatures: string[]) {
  const parsed = Hypothesis.safeParse(input);
  if (!parsed.success) return { ok: false as const, reason: "schema" };
  const copy = Object.values(parsed.data.assignments).join(" ");
  if (prohibited.test(copy)) return { ok: false as const, reason: "unapproved claim" };
  if (approvedFeatures.length === 0) return { ok: false as const, reason: "empty feature catalog" };
  return { ok: true as const, value: parsed.data };
}

This example illustrates layered checks, not a complete semantic validator. A blocklist alone is weak: models can phrase the same false claim in another way. Prefer claim templates and retrieval from an approved fact catalog for product, trial, and pricing statements. Human review remains necessary for new claim classes.

For API details, see OpenAI Structured Outputs. The principle applies across model providers (ONLang’s planner uses Anthropic’s Claude models): syntactic validity is necessary but insufficient.

Add semantic and rendered validation

Semantic checks compare candidates with authoritative facts. Does the referenced feature exist in this app version? Does the trial token resolve to the actual store offer? Does the annual savings statement use current prices and an approved rounding rule? Is the selected product included in the contract’s product list?

Rendered checks catch constraints that JSON cannot express. Generate snapshots for supported screen sizes, dynamic type, font scaling, dark mode, and long translations. Test screen-reader ordering and accessible labels. Check that fixed disclosures remain visible and that the purchase action works for every allowed product.

Some checks belong in CI and some in a publishing service. Keep deterministic source fixtures so a model update cannot silently change validation outcomes. Store model name, prompt version, candidate payload, validation result, reviewer, and release identifier in an audit log.

If a candidate fails, reject it rather than asking the optimizer to learn from user harm. Optimization happens only among valid, approved arms. Dynamic paywall compliance provides the store and disclosure checklist that should inform these gates.

Separate proposal, selection, and evaluation

A language model is good at producing plausible alternatives. A bandit is designed to allocate traffic among alternatives using observed outcomes. Neither performs the other’s job automatically. Keep the systems separate so statistical behavior remains inspectable.

For binary purchase conversion, each approved composition can be modeled as a Beta-Bernoulli arm. After s successes and f failures from prior Beta(α, β), the posterior is Beta(α + s, β + f). Thompson Sampling draws one sample per arm and selects the largest for the next eligible impression. Allocation changes as evidence accumulates. When compositions are combinations of several hypotheses, independent arms spread traffic thin; ONLang’s optimizer therefore fits a factored Bayesian logistic model over the variants and applies Thompson Sampling to that posterior.

This does not prove long-term superiority or causal incrementality by itself. Delayed outcomes, non-stationary acquisition, repeated users, and adaptive data collection complicate inference. A persistent holdout and predeclared analysis windows remain important. Bayesian bandits for paywalls and holdout methodology cover those limits.

The model should not continuously rewrite arms while an experiment is running unless the analysis explicitly supports that non-stationary candidate set. Freeze a versioned hypothesis set, validate it, then evaluate it. New proposals belong in a new release or experiment phase.

Keep humans at the boundary that matters

Human review should focus on the hypothesis space and claim policy rather than individually hand-coding every variation. Reviewers approve component types, permitted copy fields, product facts, prohibited persuasion patterns, and guardrail metrics. High-risk categories may require review of every generated candidate.

Do not let observed conversion automatically expand the search space. A model might discover that an exaggerated claim converts better; the optimizer cannot infer legal or ethical permission from revenue. Constraints must remain external to the reward.

Define stop conditions beyond purchase conversion: refund rate, early cancellation, support complaints, restore failures, performance regressions, and accessibility defects. Some are delayed, so immediate bandit rewards need complementary fixed-window analyses.

A kill switch must stop delivery without generating a replacement candidate on the fly. ONLang supports onlang kill paywall --reason "INC-12" and application-owned fallback on killed or failed outcomes. This keeps incident response deterministic.

Integrate with native SDKs and existing billing

ONLang’s registry and CLI make the finite boundary concrete. Create a token hypothesis, lint it, publish it, and start an experiment:

onlang hypothesis create --id paywall.cta.copy --kind tokens --screen paywall \
  --key cta.title --rationale "Name the outcome, not the step" \
  --variant "outcome=Get my plan" --variant "trial=Try Pro free for {{trial.annual}}"
onlang lint
ONLANG_TOKEN=onl_sk_… onlang publish
ONLANG_TOKEN=onl_sk_… onlang experiment create --placement paywall --holdout 0.1 --start

The application still owns StoreKit 2, Play Billing, RevenueCat, or app-provided purchase functions. Generated text cannot replace entitlement code. Use the iOS guide, Android guide, or React Native guide to register the actual native components.

For teams moving an existing screen into this model, the migration blueprint starts with parity and fallback before adding optimization. For a broader architectural view, the Swift and Kotlin SDUI guide shows why safe deserialization is only one layer.

A practical adoption sequence

First, define one token and two human-written variants. Validate and run the full publish, exposure, purchase, and kill path. Second, add semantic checks against store and feature facts. Third, let an LLM propose candidates into the same schema, with human approval. Automating approval for a narrow, low-risk claim class is a later decision; in ONLang, every proposal currently needs a person’s approval.

Measure the review rejection rate and reasons. If many candidates invent claims, improve the fact catalog or narrow the prompt rather than adding an ever-growing regex list. If candidates are valid but indistinguishable, generation may add little value; a smaller human-written set can be statistically and operationally better.

Generative UI is most useful when creativity is abundant and trust is scarce. Finite contracts supply that trust boundary. They let teams explore messaging without turning every experiment into a software-release or compliance event.

ONLang’s 14-day trial provides full functionality for each new app, including production and real users, with no card required at signup. Start the trial and test one bounded hypothesis before deciding whether generative proposals belong in your paywall workflow.

Sources