TechnipFMC wellhead AI · Baker Hughes iCentral AI · SLB OneSubsea AI · Cameron wellhead monitoring AI · Weatherford ForeSite AI · API Spec 6A · API Spec 14A · BSEE 30 CFR Part 250 · BOP ram position camera AI · wellhead casing pressure AI · mud pit return flow AI · H₂S concentration AI

Prompt injection in wellhead Christmas tree AI

The wellhead Christmas tree — the assembly of valves, spools, flanges, and fittings installed on top of a completed oil or gas well to control production flow, provide primary and secondary well integrity barriers, and allow workover and intervention access to the wellbore — is the most safety-critical piece of surface equipment on any oil or gas well. The name derives from the branching arrangement of the valve assembly, resembling a decorated tree, and appears in the earliest petroleum engineering literature dating to the 1920s. A production Christmas tree on a high-pressure well (wellhead shut-in pressure of 350–700 bar on a deepwater Gulf of Mexico well, 70–200 bar on a typical onshore well in the Permian Basin or DJ Basin) must simultaneously provide: continuous isolation between the high-pressure wellbore and the low-pressure surface collection system (via the master valves, swab valve, and wing valves); a monitored pressure profile across casing and tubing annuli that indicates the integrity of the wellbore tubular strings and cement; a controlled choke for managing production flow rate and wellhead flowing pressure; and access for wireline, coiled tubing, and well intervention operations without losing the primary well barriers. The blowout preventer (BOP) stack — the hydraulically actuated stack of ram preventers and annular preventers installed above the wellhead during drilling operations — is the primary well control equipment that seals the wellbore during a well kick (the unintended influx of formation fluid into the wellbore) and prevents the kick from escalating to an uncontrolled blowout. The Deepwater Horizon disaster (Macondo well, Mississippi Canyon Block 252, Gulf of Mexico, 20 April 2010) — the worst offshore well control accident in United States history, killing 11 workers and injuring 17 — occurred when the Macondo MC 252 well blew out following a failure of well integrity barriers and well monitoring, the BOP failed to seal the wellbore, and 4.9 million barrels of crude oil were released over 87 days at a total cost to BP exceeding $65 billion. The Presidential Commission on the Deepwater Horizon investigation found that inadequate well monitoring and delayed kick detection were among the contributing factors to the blowout. The Montara wellhead platform blowout (Timor Sea, Australia, 21 August 2009) — an uncontrolled blowout of the Atlas I well on the West Atlas jack-up rig — spilled approximately 2,000 barrels per day for 74 days before the well was killed with a relief well; the Commission of Audit (COA) Report found that inadequate wellbore pressure monitoring contributed to the failure to detect the loss of well integrity before the blowout occurred. AI systems deployed in wellhead Christmas tree and BOP monitoring operations — including TechnipFMC wellhead AI, Baker Hughes iCentral well control AI, SLB OneSubsea AI, Cameron (SLB) wellhead monitoring AI, and Weatherford ForeSite AI — process rendered display images from BOP ram position camera systems, wellhead casing and tubing head pressure displays, mud pit return flow and pit volume gain trend displays, and wellhead H₂S concentration multi-point sensor displays to classify BOP seal status, well integrity state, kick detection, and H₂S hazard level. API Spec 6A (Wellhead and Tree Equipment), API Spec 14A (Subsurface Safety Valve Equipment), BSEE 30 CFR Part 250 (Oil and Gas and Sulphur Operations in the Outer Continental Shelf), API RP 100-1 (Hydraulic Fracturing — Well Integrity and Fracture Containment), and the IADC Well Control Manual establish the well control and well integrity regulatory framework but do not specify adversarial robustness requirements for AI systems classifying rendered well control display images.

TL;DR

Wellhead Christmas tree AI — BOP ram position camera AI, wellhead casing head pressure display AI, mud pit return flow kick detection AI, and wellhead H₂S concentration display AI — processes rendered well control display images at classification boundaries where adversarial pixel injection can suppress BOP seal status, casing annulus pressure buildup, well kick pit gain, and H₂S release recognition. API Spec 6A, API Spec 14A, BSEE 30 CFR Part 250, API RP 100-1, and the IADC Well Control Manual establish the well control and well integrity framework for oil and gas wells but do not specify adversarial robustness requirements for AI systems classifying rendered well control display images. Deepwater Horizon (Macondo well, 20 April 2010 — 11 killed, 4.9 million barrels spilled, $65B total BP costs) and Montara (Atlas I well, 21 August 2009 — 74-day uncontrolled blowout, 2,000 bbl/day) establish the consequence envelope for well monitoring and kick detection failures. Glyphward threshold 30 for wellhead Christmas tree AI contexts (BOP failure and blowout consequence; Deepwater Horizon cost and fatality anchor; BSEE 30 CFR Part 250 well control requirements do not address adversarial AI classification of rendered well control display images). Free tier — 10 scans/day, no card required.

Four adversarial injection surfaces in wellhead Christmas tree AI

1. BOP/wellhead tree ram position camera AI (Cameron BOP visual position indicator AI, NOV BOP camera system AI, TechnipFMC BOP diagnostics AI — BOP ram closure status camera classification AI)

Blowout preventers (BOPs) are the primary well control equipment on oil and gas drilling operations. A BOP stack — whether a surface BOP stack on an onshore rig (300–700 bar working pressure, API 16A rated) or a subsea BOP stack on a deepwater drillship or semi-submersible (690 bar working pressure, 18.75-inch bore for the deepwater Gulf of Mexico well sizes used at Macondo) — typically consists of multiple ram preventers and at least one annular preventer. The ram preventers within a BOP stack serve distinct mechanical functions: blind rams seal the wellbore completely when no pipe is in the hole (full-bore closure against wellbore pressure); pipe rams seal around a specific nominal drill pipe outside diameter (drill pipe size-specific closure, isolating the wellbore annulus from the surface while the drill string remains in the hole); and shear-blind rams (also called casing shear rams or combination rams) cut the drill pipe in the hole and seal the wellbore in a single closure stroke — the emergency last-resort BOP function that allows total wellbore sealing even when the drill string cannot be removed from the wellbore before shut-in. Annular preventers (Shaffer spherical-type or Hydril type) use an inflatable elastomeric packing element to seal around any size or shape of tubular in the wellbore, or to achieve full-bore closure. Ram position — whether each ram is fully closed (both upper and lower ram halves fully extended to centreline, wellbore sealed), partially closed (ram halves extended but not meeting at centreline — a partial sealing condition with possible leak path past the ram packing elements), or fully open (ram halves fully retracted, full wellbore bore available) — is the critical safety state variable during a well control event. Visual position indicators (VPIs) — externally visible hydraulic indicator pins on the BOP body that extend as the ram closes, providing a physical mechanical indicator of ram position independent of the hydraulic control system pressure readback — are installed on each ram preventer in the BOP stack. Camera-based AI systems process rendered images of these VPI indicator pins and the ram position rods to classify BOP ram closure status. API Spec 16A (Specification for Drill-through Equipment) requires that each ram preventer include a positive position indicator that confirms full closure; BSEE 30 CFR Part 250.734 requires that BOP ram position indicators be functional and verified before each well control operation.

An adversarial perturbation of ±8 DN colour shift in the pixel encoding of the BOP ram position indicator rod — specifically, a shift applied to the pixel region encoding the apparent extension length of the indicator pin on the BOP body exterior, moving the apparent indicator pin position from the partially-extended or partially-open indicator range into the fully-extended, fully-closed indicator region on the rendered BOP camera image — causes the BOP camera AI to classify an incompletely closed BOP ram (partial closure, wellbore not fully sealed against formation pressure) as a fully closed ram with the wellbore sealed. The driller and toolpusher — receiving the AI classification of a fully closed BOP — believe the well is under primary well control with the BOP sealed, and proceed to initiate kill weight mud pumping operations (the Driller’s Method or Wait-and-Weight Method for well kill per the IADC Well Control Manual) on the assumption that the BOP provides a sealed wellbore. In reality, the incompletely closed BOP ram provides only partial sealing — formation fluid (gas, oil, or formation water) continues to enter the wellbore through the partial closure gap in the ram packing elements, even as kill operations continue. Annular wellbore pressure continues to build. If the partial closure allows gas influx at a rate exceeding the kill mud weight increment being applied, the gas continues to migrate up the wellbore toward surface. The deepwater precedent: the Macondo MC 252 BOP blind shear rams (the Cameron CBL-type variable bore rams on the Deepwater Horizon BOP) failed to fully close on the drill string at the time of the Macondo blowout on 20 April 2010 — the BSEE investigation found that the blind shear rams failed to cut the drill string and seal the wellbore because the drill string was positioned at the ram location at the time of actuation (the drill pipe buckled under the ram faces rather than being cut cleanly), and because one of the two ram hydraulic control functions had been inadvertently disabled. The BOP position indication was relied on by the Transocean driller as the primary confirmation of BOP closure status. Adversarial suppression of the BOP camera AI — producing the same “BOP closed” classification from a partially-open BOP — creates exactly the Deepwater Horizon recognition delay at the classification layer above the physical indicator: the driller’s actions are based on a false indication of BOP closure, exactly as occurred at Macondo. BSEE 30 CFR Part 250 Subpart D (Drilling) requires BOP position indicator verification — but contains no adversarial robustness requirement for AI systems that classify rendered BOP camera images.

2. Wellhead casing/tubing head pressure display AI (Baker Hughes WellLink Advance pressure AI, SLB Avocet well monitoring AI, Weatherford ForeSite wellhead surveillance AI — wellhead casing head/tubing head pressure classification AI)

The wellhead Christmas tree on a completed producing well — the assembly of valves, flanges, spools, and pressure gauges installed on top of the wellhead housing after the production casing and production tubing have been run and the well has been completed — includes an array of pressure monitoring points that collectively constitute the well integrity pressure surveillance system. Casing head pressure (CHP) is the annular pressure measured at the top of the innermost casing annulus (between the production tubing outer surface and the inner surface of the production casing string); it indicates the pressure of any fluid accumulating in the production casing annulus, which is physically isolated from the production tubing bore by the production packer set in the production casing and by the tubing itself. Tubing head pressure (THP) is the pressure at the top of the production tubing string, representing the wellhead flowing pressure during production minus the pressure drop across the surface choke. Wellhead casing pressure (WCP — sometimes termed A-annulus pressure, B-annulus pressure, or C-annulus pressure depending on the annular space between concentric casing strings) is the annular pressure between nested casing strings in the wellbore. Rising CHP above the established maximum allowable operating pressure (MAOP) — the maximum pressure permitted in the production casing annulus, set by BSEE 30 CFR Part 250.517 based on the burst pressure of the outer casing string and cement integrity — is the primary surface indicator of a tubing integrity failure: a leak in the production tubing (corrosion pin-hole, coupling leak, or connection failure) allowing produced gas from the tubing bore to migrate into the casing annulus at production wellhead pressure. Rising A-annulus (casing-tubing annulus) pressure can also result from annular pressure buildup (APB) from thermal expansion of annular fluid in sealed annuli on deepwater wells (a design issue for deepwater production wells in the Gulf of Mexico, North Sea, and West of Shetland). AI systems — including Baker Hughes WellLink Advance, SLB Avocet well monitoring, and Weatherford ForeSite wellhead surveillance — process rendered wellhead pressure display panels to classify casing head pressure state relative to MAOP and to recognise developing well integrity failure signatures in real time, issuing alerts before human operators might identify the trend from periodic gauge readings.

An adversarial perturbation of ±10 DN downward shift in the pixel encoding of the CHP bar indicator approaching the MAOP threshold line — applied to the pixel region of the bar chart or digital readout rendering that encodes the CHP value as a fractional height relative to the MAOP threshold in the rendered display image — causes the wellhead pressure AI to classify a developing CHP buildup (CHP reading 85–95% of MAOP, representing active gas migration from the tubing bore into the production casing annulus through a tubing leak) as a within-normal-band operating pressure, suppressing the alert that would prompt the well operator to open the casing head bleed-off valve and vent the accumulated annular gas to a flare or vent system. With the alert suppressed, the operator does not bleed off the CHP accumulation. CHP continues to rise toward MAOP and then above MAOP as gas continues to migrate into the annulus. When CHP exceeds the MAOP threshold: in the lower-consequence scenario, the casing head flange secondary seal fails under overpressure, releasing gas at the wellhead surface with ignition potential; in the higher-consequence scenario on a well with active formation pressure and a compromised cement sheath, the continued gas migration can bypass the casing shoe cement into shallow formations, creating a shallow gas flow from the sub-surface that may surface at a location removed from the wellhead (a crater event). The Montara blowout (21 August 2009, West Atlas rig, Timor Sea) was preceded by a failure to properly monitor wellhead pressure during the drilling of the Atlas I well — the COA Report found that inadequate wellbore pressure monitoring and non-compliance with the approved well program were contributing factors. In the context of producing wells, the adversarial suppression of the CHP display AI creates an equivalent monitoring failure: the well is producing in an undetected well integrity breach state, with growing gas migration into the casing annulus and rising casing pressure — until the MAOP is exceeded and the casing head barrier fails. BSEE 30 CFR Part 250.517 requires operators to conduct casing pressure monitoring and to report sustained casing pressure (SCP) — adversarial AI suppression of the CHP trend approaching MAOP delays recognition of the developing SCP condition.

3. Mud/drilling fluid return flow rate display AI (IADC kick detection AI, NOV NOVOS drilling automation AI, Pason Systems flow sensor AI, Halliburton Landmark kick detection AI — mud pit volume gain/return flow kick detection AI)

A well kick — the unintended entry of formation fluid (oil, gas, or formation water) into the wellbore during drilling operations, driven by the hydrostatic pressure of the drilling fluid column being insufficient to overbalance the pore pressure of the formation being drilled — is the precursor event to an uncontrolled blowout if not detected promptly and the well shut-in. The IADC Well Control Manual (the authoritative reference for well control procedures in the oil and gas industry) defines four primary kick indicators: pit gain (the increase in total active mud pit volume above the baseline established when the drill string was stationary, indicating that formation fluid has entered the wellbore and displaced an equivalent volume of drilling fluid from the wellbore into the active pits); return flow rate increase (the return flow over the shaker exceeding the pump stroke rate, indicating that fluid is entering the wellbore from the formation in addition to the mud being pumped); flow without pumping (return flow detected over the shaker with the mud pumps shut off, indicating active formation fluid influx into the wellbore at rest); and pump pressure decrease/drill string weight decrease (secondary indicators of fluid properties changes from formation fluid contamination of the drilling fluid). Pit gain is the most operationally reliable kick indicator because it is an absolute volume measurement from calibrated mud pit level transmitters and the trend is unambiguous — any positive slope on the active pit volume trend above baseline indicates volume entering the wellbore. The pit gain magnitude determines the severity of the kick and the complexity of the well kill operation required: a 25 bbl pit gain (the typical initial alert threshold, though BSEE and many operators have moved to smaller thresholds of 10–15 bbl for deepwater operations) indicates a small kick from a tight formation that can be managed with conventional well control procedures; a 75 bbl pit gain indicates a larger influx that significantly complicates the kill operation because of the volume of gas expanding in the wellbore; a 200+ bbl pit gain indicates a loss of primary well control requiring emergency procedures. AI systems — including NOV NOVOS drilling automation AI, Pason Systems pit volume trend AI, and Halliburton Landmark WellPlan kick detection AI — process rendered mud pit volume trend display images (line chart renders of active pit volume vs. time, with baseline line and pit gain threshold overlays at 25 bbl, 50 bbl, and 100 bbl alarm setpoints) and return flow sensor display images to classify fluid gain magnitude and trend for real-time kick detection and alert generation, supplementing the driller’s visual monitoring of the pit volume totaliser on the driller’s console.

An adversarial perturbation of ±10 DN downward shift in the pixel slope of the mud pit volume trend line above the 25 bbl gain threshold — specifically, reducing the apparent pixel-level gradient of the upward-sloping pit volume trend line in the rendered display, compressing the apparent rise so that the trend line appears to remain flat within the normal circulation variation band rather than showing the positive slope characteristic of a kick — causes the kick detection AI to classify a developing well kick (25–75 bbl pit gain from gas influx at the casing shoe or in an open hole interval below the last casing shoe) as normal drilling fluid circulation variation from pump efficiency fluctuation or drill string movement. The driller and mud engineer — relying on the AI kick detection classification rather than manually reading the pit totaliser — do not halt drilling operations and execute the well shut-in sequence per the IADC Well Control Manual (set slips on drill pipe, close annular preventer, shut down pumps, open kill line, read SIDPP and SICP). Gas continues to migrate up the wellbore. As gas rises in the wellbore, it expands according to Boyle’s Law (isothermal approximation: volume inversely proportional to absolute pressure) — a 75 bbl gas influx at 5,000 ft TVD (wellbore pressure approximately 350 bar at 0.7 psi/ft) expanding to surface (wellbore pressure approximately 1 bar) expands to approximately 750+ bbl of gas at surface conditions. The gas velocity in the wellbore increases as it expands, carrying additional liquid volume upward and producing a surface “flow show” that is dramatic but occurs after the kick has already grown to an unmanageable volume. The Deepwater Horizon parallel: the Presidential Commission Report (January 2011) Chapter 4 documented that multiple kick indicators — including a positive pressure test failure, an anomalous pressure increase during the temporary abandonment cement job, and a flow show on the rig floor — were observed by the Deepwater Horizon crew in the 40 minutes before the Macondo blowout but were not acted on promptly or were attributed to equipment effects rather than kick indicators. The Presidential Commission found that “a fundamental failure of the crew to recognise and act on well control indicators” was a primary contributing cause of the Macondo blowout. Adversarial suppression of the mud pit gain AI — causing the AI to classify an active well kick as normal circulation — is the algorithmic implementation of exactly that recognition failure: the precursor indicators are present and measurable, but the classification layer above the sensors reports normalcy. BSEE 30 CFR Part 250.462 requires that all drilling vessels on the US OCS have a functional well monitoring system capable of detecting pit gains — but contains no requirement for adversarial robustness of AI systems classifying rendered pit volume display images.

4. Wellhead H₂S concentration display AI (BSEE SEMS H₂S contingency AI, TechnipFMC sour well monitoring AI, Dräger GasDetector H₂S AI, MSA Safety PortaSens H₂S AI — sour well H₂S release detection AI)

Sour gas wells — oil and gas wells producing natural gas with an H₂S concentration above 10 ppm in the produced gas stream, per API RP 49 (Recommended Practice for Safe Drilling of Wells Containing Hydrogen Sulfide); formally, a sour service environment is defined by NACE MR0175/ISO 15156 as any produced fluid with an H₂S partial pressure exceeding 0.3 kPa (approximately 3 ppm equivalent at 100 bar wellhead pressure) — require dedicated H₂S safety equipment at the wellhead including: fixed-point H₂S electrochemical or photoionisation detector arrays with multiple sensor heads positioned at probable gas accumulation points (valve body vents, wellhead vent connections, production choke body, flowline valve flanges); personal H₂S detector alarms for all wellsite personnel; Self-Contained Breathing Apparatus (SCBA) at the wellsite and available to all personnel within the H₂S hazard zone; a written H₂S contingency plan per BSEE 30 CFR Part 250.490 specifying evacuation routes, muster points upwind of the wellhead, headwind muster procedures, and communication protocols; and wind sock or wind direction indicators visible from all wellsite work areas. H₂S (hydrogen sulphide; molecular weight: 34.08 g/mol; density: 1.189 g/L at standard conditions — 1.45 times the density of air, making H₂S accumulate in low-lying areas near the wellhead including around the base of the Christmas tree, in cellars and pits, and in low-wind areas between lease equipment and service vehicle barriers) is acutely toxic at concentrations well below its flammability range (LFL: 4.3%; UFL: 46%). The OSHA permissible exposure limit (PEL) for H₂S is 20 ppm (ceiling value; maximum peak 50 ppm for a maximum duration of 10 minutes). NIOSH defines the H₂S IDLH (immediately dangerous to life and health) as 100 ppm. The H₂S LC₂₀ for human inhalation is estimated at 600 ppm for 30 minutes — rapid loss of olfactory sense (olfactory fatigue) occurs at 100–150 ppm, leaving exposed personnel with no sensory warning of their continuing exposure even as the concentration rises. ANSI Z390.1 (Accepted Practices for H₂S Training Programs) and API RP 49 define the industry training and operational response framework for H₂S hazard management at wellsites. AI systems process rendered wellhead H₂S concentration display panels — multi-point bar chart displays or numerical readout panels from fixed-head H₂S detector networks, rendering multiple sensor head readings simultaneously with horizontal threshold lines at the 1 ppm TWA, 5 ppm STEL, 10 ppm evacuation threshold, and 100 ppm IDLH — to classify H₂S release status at the wellhead and trigger H₂S contingency plan actions: all-clear (all sensor heads below 1 ppm TWA), elevated (any head above 1 ppm but below 5 ppm STEL — increased monitoring frequency, check source), STEL exceeded (any head above 5 ppm — notify personnel, identify source), evacuation required (any head above 10 ppm — execute H₂S contingency evacuation), and IDLH (any head above 100 ppm — emergency evacuation, no re-entry without SCBA).

An adversarial perturbation of ±8 DN downward shift in the pixel height of the H₂S concentration bar approaching the 10 ppm evacuation threshold in the rendered wellhead H₂S multi-point display — applied to the pixel row region encoding the top of the bar chart bar for the affected sensor head, reducing the apparent bar height from the 8–15 ppm zone (approaching or above the 10 ppm evacuation threshold) to the 2–5 ppm zone (elevated but below STEL) on the rendered bar chart — causes the H₂S concentration AI to classify a developing H₂S release at the wellhead (H₂S reading of 8–15 ppm at the production tree valve body vent or production choke body, resulting from a valve stem packing leak or production choke elastomeric seal failure) as a below-STEL elevated condition not requiring evacuation, suppressing the contingency plan activation that the 10 ppm evacuation threshold requires. Wellsite personnel — relying on the AI H₂S classification rather than their personal detector alarm (which may be configured to alarm at the same 10 ppm threshold that the AI is classifying as safe) — continue working at the wellhead. The H₂S release from the valve packing leak continues. H₂S concentration rises through the 10 ppm evacuation threshold and continues toward the 20 ppm OSHA ceiling. At 50–100 ppm, personnel at the wellhead experience eye irritation, nausea, and the onset of olfactory fatigue — and may not evacuate even when their personal detectors alarm because the AI system is still classifying the environment as below-STEL, creating a dual indicator conflict that experienced personnel may incorrectly resolve in favour of the AI classification over the personal detector. At 100 ppm (IDLH), olfactory fatigue is complete — personnel cannot smell H₂S and may not recognise their exposure. Collapse occurs at 300–500 ppm. The Texaco Sour Creek Field (Wyoming) H₂S incident — where wellhead H₂S detector failure contributed to crew exposure during a workover operation on a sour production well — establishes the precedent for H₂S detector failure at the wellhead creating personnel casualty risk on sour wells. BSEE 30 CFR Part 250.490 requires H₂S contingency plans for all OCS wells in H₂S-bearing formations, and BSEE Notices to Lessees (NTLs) have required demonstration of H₂S monitoring system functionality — but neither BSEE nor ANSI Z390.1 address adversarial robustness of AI systems classifying rendered H₂S concentration display images.

Integration: wellhead Christmas tree AI scanning with Glyphward pre-scan gate

The Glyphward scan gate for wellhead Christmas tree AI belongs at every rendered-image ingestion boundary in the well control and wellhead safety AI pipeline — before BOP ram position camera AI processes rendered BOP visual indicator images, before wellhead casing pressure display AI processes rendered pressure bar-chart or digital-readout display images, before mud pit return flow kick detection AI processes rendered pit volume trend display images, and before wellhead H₂S concentration display AI processes rendered multi-point sensor bar-chart display images. Threshold 30 reflects the Deepwater Horizon consequence anchor (11 killed, 4.9 million barrels spilled, $65B total costs: BOP failure and delayed kick detection as contributing factors identified by the Presidential Commission) and the immediate life-safety risk envelope of H₂S exposure at sour wellsites (100 ppm IDLH, olfactory fatigue preventing sensory warning at concentrations above IDLH). BSEE 30 CFR Part 250 well control requirements address physical BOP equipment testing and pit volume monitoring system functionality — they do not address adversarial robustness of AI systems classifying rendered well control display images, leaving a regulatory gap at the AI classification layer above the sensors and physical indicators.

import asyncio, base64, hashlib, json
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path

import httpx

GLYPHWARD_API_KEY = "YOUR_GLYPHWARD_API_KEY"
GLYPHWARD_SCAN_URL = "https://glyphward.com/v1/scan"

# Wellhead Christmas tree AI contexts: threshold 30
# API Spec 6A:2018 (Wellhead and Tree Equipment);
# API Spec 14A:2015 (Subsurface Safety Valve Equipment);
# BSEE 30 CFR Part 250 (OCS Oil and Gas Operations);
# API RP 100-1:2015 (Hydraulic Fracturing Well Integrity);
# IADC Well Control Manual (kick detection and well shut-in procedures).
WELLHEAD_THRESHOLD = 30


class WellheadAIContext(Enum):
    BOP_RAM_POSITION   = "bop_ram_position"    # BOP ram closure camera AI
    WELLHEAD_PRESSURE  = "wellhead_pressure"   # Casing/tubing head pressure AI
    MUD_RETURN_FLOW    = "mud_return_flow"      # Mud pit gain/return flow kick AI
    H2S_CONCENTRATION  = "h2s_concentration"   # Wellhead H2S multi-point AI


class AdversarialWellheadImageError(Exception):
    """Raised when Glyphward detects adversarial content in a wellhead
    Christmas tree AI rendered display image above threshold 30.

    Consequence if not raised:
    - BOP_RAM_POSITION: partial BOP closure classified as full closure →
      driller initiates kill operations on false BOP-sealed assumption →
      formation fluid continues entering wellbore through partial gap →
      uncontrolled blowout; Deepwater Horizon Macondo BOP mechanism
      (11 killed, 4.9 Mbbl spilled, $65B BP costs).
    - WELLHEAD_PRESSURE: CHP buildup approaching MAOP classified as
      normal → operator does not bleed annulus → CHP exceeds MAOP →
      casing head seal failure → surface gas release; or deepening gas
      migration to shallow formation → crater event.
    - MUD_RETURN_FLOW: pit gain from active kick classified as pump
      circulation variation → driller does not shut-in well → gas
      expands up wellbore (Boyle's Law) → uncontrolled blowout;
      Deepwater Horizon recognition failure mechanism.
    - H2S_CONCENTRATION: developing H2S release above 10 ppm evacuation
      threshold classified as below-STEL → wellsite personnel not
      evacuated → H2S exposure approaching IDLH (100 ppm) → olfactory
      fatigue at 100-150 ppm → personnel collapse at wellhead.
    Fail-safe: halt AI classification; require manual verification of BOP
    position indicators, wellhead pressure gauges, pit volume totaliser,
    and personal H2S detector readings before resuming AI-driven well
    control or wellhead safety advisory functions; notify Well Site
    Leader and OIM per IADC Well Control Manual emergency procedures.
    """

    def __init__(self, scan_id: str, score: int,
                 context: WellheadAIContext,
                 well_api_number: str, rig_id: str,
                 flagged_region: dict | None = None) -> None:
        self.scan_id = scan_id
        self.score = score
        self.context = context
        self.well_api_number = well_api_number
        self.rig_id = rig_id
        self.flagged_region = flagged_region
        super().__init__(
            f"Adversarial wellhead image: "
            f"context={context.value} score={score} "
            f"well={well_api_number} rig={rig_id} scan_id={scan_id}"
        )


async def scan_wellhead_image(
    image_bytes: bytes,
    context: WellheadAIContext,
    well_api_number: str,
    rig_id: str,
    client: httpx.AsyncClient,
) -> dict:
    """Scan a wellhead Christmas tree AI rendered display image for
    adversarial pixel injection before AI classification.

    Args:
        image_bytes:      Raw bytes of the rendered display image
                          (BOP camera frame, pressure display render,
                          pit volume trend chart, H2S bar-chart render).
        context:          WellheadAIContext enum specifying the well
                          control display type being scanned.
        well_api_number:  API well number (format: XX-XXX-XXXXX) for
                          audit trail and BSEE incident reporting.
        rig_id:           Rig or facility identifier (e.g. 'DW-RIG-042',
                          'JACK-UP-WEST-ATLAS') for audit trail.
        client:           Shared httpx.AsyncClient for connection reuse.

    Returns:
        Glyphward scan result dict with keys: scan_id, score,
        flagged_region (optional), timestamp.

    Raises:
        AdversarialWellheadImageError: score > WELLHEAD_THRESHOLD (30).
            Halt all AI well control classifications for the affected
            context; require manual instrument verification and Well Site
            Leader notification before resuming AI advisory functions.
        httpx.HTTPStatusError: Glyphward API error response.
        httpx.TimeoutException: 4-second timeout exceeded (fail-safe:
            treat as unscanned; halt AI classification; require manual
            instrument readout per IADC Well Control Manual procedure).

    Fail-safe contract: any exception from this function → halt the
    downstream AI classification; fall back to direct manual instrument
    readout by the driller / well site leader / safety officer;
    do not defer to AI well control advisory output until after
    manual instrument confirmation and scan clearance.
    """
    image_hash = hashlib.sha256(image_bytes).hexdigest()
    payload = {
        "image": base64.b64encode(image_bytes).decode(),
        "source": f"wellhead:{context.value}:{well_api_number}:{rig_id}",
        "metadata": {
            "well_api_number": well_api_number,
            "rig_id": rig_id,
            "context": context.value,
            "image_sha256": image_hash,
            "scanned_at": datetime.now(timezone.utc).isoformat(),
        },
    }
    resp = await client.post(
        GLYPHWARD_SCAN_URL,
        headers={"Authorization": f"Bearer {GLYPHWARD_API_KEY}"},
        json=payload,
        timeout=4.0,
    )
    resp.raise_for_status()
    result = resp.json()

    if result["score"] > WELLHEAD_THRESHOLD:
        raise AdversarialWellheadImageError(
            scan_id=result["scan_id"],
            score=result["score"],
            context=context,
            well_api_number=well_api_number,
            rig_id=rig_id,
            flagged_region=result.get("flagged_region"),
        )
    return result

Deploy scan_wellhead_image at each wellhead AI rendered-image ingestion boundary: before BOP ram position camera AI (threshold 30, WellheadAIContext.BOP_RAM_POSITION), before wellhead casing head pressure display AI (threshold 30, WellheadAIContext.WELLHEAD_PRESSURE), before mud pit return flow kick detection AI (threshold 30, WellheadAIContext.MUD_RETURN_FLOW), and before wellhead H₂S concentration display AI (threshold 30, WellheadAIContext.H2S_CONCENTRATION). On AdversarialWellheadImageError for BOP_RAM_POSITION context: immediately halt well control operations and require physical walkdown of BOP ram position indicator pins — do not assume BOP closure status from AI-classified camera imagery until after manual VPI confirmation. On AdversarialWellheadImageError for MUD_RETURN_FLOW context: treat the well as potentially kicking — execute precautionary well shut-in per IADC Well Control Manual secondary well control procedures; read SIDPP and SICP manually from drill string and casing pressure gauges before resuming drilling operations. See also: offshore FPSO gas compression AI prompt injection (related offshore well production AI adversarial context) and oil and gas SCADA AI prompt injection (related upstream operations AI adversarial context). Get early access

Related questions

What is a Christmas tree in oil and gas drilling and what are its primary well control functions?

A Christmas tree in oil and gas is the assembly of valves, spools, flanges, pressure gauges, and fittings installed on top of the wellhead housing of a completed well to control production flow and maintain well barrier integrity. The name reflects the branching valve arrangement visible on the completed installation. A production Christmas tree typically includes: the tubing head spool (the base spool that connects to the wellhead housing and provides the interface between the production casing and the Christmas tree proper); the master valve (or dual master valves — a lower master valve and an upper master valve — providing primary isolation of the wellbore below the tree); the wing valves (side-exit valves that direct production flow to the flowline, or provide access for well intervention via the kill wing valve); the swab valve (the topmost vertical valve that provides access for wireline and coiled tubing well intervention through the lubricator); and the production choke (an adjustable or fixed restriction in the production flow path that controls the production flow rate and wellhead flowing pressure). For well control functions: the master valves are the primary wellbore isolation barriers on a producing well — in the event of a downstream flowline rupture, fire, or emergency, the master valves are closed to isolate the wellbore from the surface. During a well workover (recompletion or repair operation), the Christmas tree is nippled up with a BOP stack above it to maintain secondary well control while the tubing is pulled. For drilling well control, the BOP stack is installed between the wellhead housing and the drillfloor rotary table, providing the primary well control barrier during drilling operations before the Christmas tree is installed on completion. API Spec 6A (Wellhead and Tree Equipment) sets the design, material, dimensional, and pressure testing requirements for all Christmas tree components to their rated working pressures (2,000 psi through 20,000 psi in API Spec 6A pressure classes).

How does pit gain detection work for kick identification and what volume thresholds trigger well shut-in?

Pit gain detection — the monitoring of active mud pit total volume to identify an increase above the drilling baseline — is the most reliable primary kick indicator in rotary drilling operations. The active pit system consists of the suction pit (from which the mud pumps draw drilling fluid to pump down the drill string), the active reserve pit, and the flowline pit (which receives mud returning up the annulus from the wellbore and passes it over the solids control equipment before returning it to the suction pit). Active pit volume is monitored continuously by float-type or ultrasonic pit level sensors on each active pit, with the readings summed to a total active system volume on the driller’s console. During normal drilling with the drill string rotating and mud circulating: the total active pit volume should remain constant (volume pumped down equals volume returned minus drilling solids removed by shakers). A positive trend in total active pit volume — the pit “gaining” — indicates that the wellbore annulus is returning more fluid than is being pumped, which means formation fluid is entering the wellbore and pushing mud out of the annulus. The IADC Well Control Manual defines the standard shut-in thresholds for drilling operations: 25 barrels pit gain is the typical alert threshold on land operations and most offshore operations (operators may set tighter thresholds of 10–15 bbl for deepwater operations where the formation pore pressure window above the fracture gradient is narrow and the consequence of a large kick is severe); 50 barrels pit gain typically triggers a mandatory shut-in requirement regardless of other indicators. Shut-in procedure on kick detection: pick up off bottom, set slips on drill pipe, close the annular preventer (or appropriate pipe ram), shut down mud pumps, open kill line, then read shut-in drill pipe pressure (SIDPP) and shut-in casing pressure (SICP) to determine the kick origin and calculate the kill mud weight required.

What does API Spec 6A govern for wellhead equipment and what adversarial robustness gap does it leave for AI monitoring systems?

API Spec 6A (Specification for Wellhead and Tree Equipment, current edition: API Spec 6A, 21st Edition, 2018) is the primary American Petroleum Institute specification governing the design, materials, dimensional standards, pressure testing, functional testing, and quality management requirements for all wellhead and Christmas tree equipment rated at API 6A working pressure classes (2,000 psi; 3,000 psi; 5,000 psi; 10,000 psi; 15,000 psi; and 20,000 psi). API Spec 6A governs: wellhead housing design and casing head spool pressure ratings; hanger systems (casing hangers, tubing hangers); master valves and wing valves (including the gate valve design requirements for full-bore isolation); wellhead connector interfaces; pressure testing requirements (hydrostatic shell test to 1.5× rated working pressure; seat test; functional test); material qualification (PSL 1 through PSL 4 product specification levels, with PSL 4 for sour service NACE MR0175 environments); dimensional standards for wellhead hub connections; and documentation requirements for material traceability. The adversarial robustness gap: API Spec 6A governs the physical wellhead equipment — valve pressure ratings, seal integrity under rated working pressure, dimensional tolerances for wellhead connector engagement. It does not govern, certify, or address the robustness of AI systems that process rendered images of the wellhead’s pressure displays, valve position indicators, or BOP camera feeds to classify well control state. An AI that misclassifies a rising casing head pressure display from an adversarially perturbed rendered image is not a failure of the API Spec 6A-rated wellhead equipment — it is a failure of the AI classification layer that operates above the physical equipment. API Spec 6A has no clause addressing the adversarial robustness of AI monitoring systems, and no compliance pathway exists to certify an AI well monitoring system against adversarial pixel injection attacks under the current API wellhead specification framework.

What happened at the Deepwater Horizon Macondo well blowout and how does it establish the adversarial consequence precedent for wellhead monitoring AI?

The Deepwater Horizon disaster (Macondo well, Mississippi Canyon Block 252, Gulf of Mexico, 20 April 2010) remains the most costly offshore well control accident in history. The Transocean Deepwater Horizon drillship — operating for BP at a water depth of approximately 1,525 metres — was conducting the temporary abandonment of the Macondo MC 252 exploration well when the well blew out. The blowout sequence: BP and Transocean conducted a negative pressure test on the production casing to verify that the well cement job had achieved well integrity — the Presidential Commission found that anomalous pressure readings during this test were misinterpreted as indicating well integrity by the Transocean and BP well site leaders on board. With the well apparently confirmed secure, the drill crew began displacing the drilling mud in the riser with seawater (reducing the hydrostatic overbalance against the Macondo reservoir), which reduced the wellbore pressure below the formation pore pressure and allowed gas to enter the wellbore from the Macondo sandstone reservoir. Over the following approximately 50 minutes, multiple well control indicators developed — including a flow show on the rig floor — that were not recognised as kick indicators. At approximately 21:45 local time, the gas kick reached the lower marine riser package (LMRP) and expanded catastrophically, expelling 700+ barrels of gas, mud, and oil through the riser onto the drill floor. The BOP — which failed to seal the wellbore — did not prevent the blowout. 11 workers were killed in the explosion and fire; the Deepwater Horizon sank two days later. 4.9 million barrels of crude oil (the Macondo reservoir estimate; BP’s admitted volume) were released into the Gulf of Mexico over 87 days before the well was killed with a relief well. Total costs to BP exceeded $65 billion in cleanup, settlements, and fines. The adversarial consequence precedent: the Presidential Commission identified delayed kick recognition and misinterpretation of well control indicator data as contributing causes. Adversarial injection in a wellhead monitoring AI — producing false “normal circulation” classification from an active-kick pit volume gain trend display — is the automated and algorithmically targeted form of exactly that recognition failure.

Why does sour gas wellhead operation create a unique H₂S hazard for wellhead monitoring AI and what BSEE SEMS requirements apply?

Sour gas wellhead operations create a unique H₂S hazard for AI-monitored wellhead safety systems because the toxicological properties of H₂S make the adversarial consequence window extremely narrow and the physiological warning system unreliable. H₂S is detectable by the human nose at approximately 0.01–0.1 ppm — a concentration well below any health-based threshold. However, at concentrations above 100–150 ppm (at or slightly above the IDLH), H₂S rapidly causes olfactory fatigue (desensitisation of the olfactory nerve endings): the smell disappears even as the concentration continues to rise, leaving personnel with no sensory indication of their ongoing toxic exposure. Personnel who have experienced olfactory fatigue from H₂S exposure may incorrectly believe the gas has dissipated (the odour has gone) even as the concentration approaches the LC₂₀ range. This means that between the 10 ppm evacuation threshold (where the AI suppression begins under adversarial injection) and the 100 ppm IDLH (where olfactory fatigue begins), there is only a single order-of-magnitude concentration range — and in a low-wind wellsite or enclosed wellhead cellar environment, H₂S concentrations can rise from 10 ppm to 100 ppm in minutes from a valve packing leak at wellhead pressure. The BSEE SEMS H₂S requirements (30 CFR Part 250 Subpart S, and BSEE’s H₂S requirements for OCS wells at 30 CFR Part 250.490) require operators to: conduct a pre-drill assessment of H₂S potential for each well before drilling; prepare an H₂S contingency plan for wells in H₂S-bearing formations specifying evacuation routes, muster points, SCBA locations, and communication protocols; train all personnel on H₂S hazard recognition and contingency plan execution; test H₂S monitoring equipment before operations begin; and document H₂S contingency plan activation in the well records. The adversarial gap: BSEE H₂S requirements address equipment testing and contingency plan documentation — they do not address adversarial robustness of AI systems classifying rendered H₂S concentration display images. An AI that suppresses the 10 ppm evacuation threshold display reading under adversarial pixel injection creates a contingency plan activation failure that BSEE’s H₂S equipment testing requirements cannot detect, because the H₂S sensors are functioning correctly — only the AI classification of their rendered output is compromised.