Compute Pressure Level 1

The Compute Pressure API provides a way for websites to react to changes in the CPU pressure of the target device, such that websites can trade off resources for an improved user experience.

Introduction

Modern applications often need to balance the trade offs and advantages of fully utilizing the system's computing resources, in order to provide a modern and delightful user experience.

As an example, many applications can render video effects with varying degrees of sophistication. These applications aim to provide the best user experience, while avoiding driving the user's device into a high pressure regime.

Utilization of [=processing units=] close to and often reaching 100% can lead to a bad user experience, as different tasks are fighting for the processing time. This can lead to slowless, which is especially noticeable with input delay. Further, a prolonged utilization close 100% can cause the [=processing units=] to heat up due to prolonged boosting, which can lead to throttling, resulting in an even worse user experience.

As a result of thermal limits, many smartphones, tablets and laptops can become uncomfortably hot to the touch. The fans in laptops and desktops can become so loud that they disrupt conversations or the users’ ability to focus.

In many cases, a device under high pressure appears to be unresponsive, as the operating system may fail to schedule the threads advancing the task that the user is waiting for. See also Use Cases.

A Note on Feature Detection

This section is non-normative.

Feature detection is an established web development best practice. Resources on the topic are plentiful on- and offline and the purpose of this section is not to discuss it further, but rather to put it in the context of detecting hardware-dependent features.

Consider the below feature detection examples:

Concepts

This specification defines the following concepts:

Processing Units

Computing devices consist of a multitude of different processing units such as the Central Processing Unit (CPU), the Graphics Processing Unit (GPU) and many specialized processing units. The latter are becoming popular such as ones designed to accelerate specific tasks like machine learning or computer vision.

Pressure sources

The specification currently defines the valid source types as global system thermals and the central [=processing unit=], also known as the CPU. Future levels of this specification MAY introduce additional [=source types=].

      enum PressureSource { "thermals", "cpu" };
    

The PressureSource enum represents the [=valid source types=]:

Sampling and Reporting Rate

The requested sampling interval represents the desired interval between samples to be obtained from the hardware, expressed in milliseconds.

Interval and frequency are inverses of each other, so the [=requested sampling interval=] can also be expressed as a requested sampling rate in Hertz (cycles per second) by dividing 1000 by the [=requested sampling interval=] value.

The sampling rate for a [=platform collector=] is defined as a rate at which the [=user agent=] obtains telemetry readings from the underlying platform, and it might differ from the pressure observers' [=requested sampling rates=]. The rate is measured in Hertz (cycles per second).

The reporting rate for a pressure observer is the rate at which it runs the [=data collection=] steps, and it will never exceed the [=sampling rate=].

The [=sampling rate=] differs from the [=requested sampling rate=] when the [=requested sampling rate=] exceeds upper or lower sampling rate bounds supported or accepted by the underlying platform and [=user agent=].

It is recommended that the [=user agent=] limits the [=reporting rate=] as outlined in [[[#rate-limiting-change-notifications]]].

In case the user didn't request a [=sampling rate=], the [=sampling rate=] is [=implementation-defined=].

Platform primitives

A pressure source is an abstract, [=implementation-defined=] interface to hardware counters or an underlying framework that provides telemetry data about a source type defined by {{PressureSource}}. A [=pressure source=] can make use of data fusion with data from additional sources if that provides more precise results.

The telemetry data provided by a [=pressure source=] is represented in this specification as a pressure source sample, a [=struct=] consisting of the following [=struct/items=]:

A [=pressure source=] has an associated latest sample, a [=pressure source sample=] or null. It is initially null.

A platform collector is an abstract interface responsible for obtaining telemetry samples from a [=pressure source=], transforming them into [=pressure states=] and providing them to the [=user agent=].

A [=platform collector=] has the following associated data:

The format of the telemetry data provided by a [=pressure source=] and stored in its [=pressure source/latest sample=]'s [=pressure source sample/data=] is [=implementation-defined=], and so is the process through which a [=platform collector=] transforms it into a [=pressure state=].

For this specification's purposes, [=platform collectors=] are scoped to a [=global object=] via the [=platform collector mapping=].

For automation purposes, a [=platform collector=] must have the ability to connect to [=virtual pressure sources=] and use their simulated [=pressure source sample/data=] as [=pressure states=] rather than raw platform data that must be transformed into an [=adjusted pressure state=].

As collecting telemetry data often means polling hardware counters, it is not a free operation and thus, it should not happen if there are no one observing the data. See [[[#life-cycle]]] for more information.

A [=platform collector=] samples data at a specific rate. A [=user agent=] may modify this rate (if possible) for privacy reasons, or ignore and fuse certain readings.

User notifications

It is RECOMMENDED that a [=user agent=] show some form of user-visible notification that informs the user when a pressure observer is active, as well as provides the user with the means to block the ongoing operation, or simply dismiss the notification.

Policy control

The Compute Pressure API defines a [=policy-controlled feature=] identified by the token "compute-pressure". Its [=policy-controlled feature/default allowlist=] is `'self'`.

Workers (dedicated and shared) adhere to the permission policy set by their owning document(s).

Shared workers often have multiple owning documents as they can be obtained by other documents with the [=same origin=]. In this case, all owning documents must be [=allowed to use=] the [=policy-controlled feature=] defined by this specification.

Dedicated workers can be created from other workers, in which case the permission policy of the first owning document (or owning documents, in case of a shared worker) up the owner chain will be used.

Internal Slot Definitions

Each [=global object=] has:

A registered observer consists of an observer (a {{PressureObserver}} object).

The [=user agent=] has:

A constructed {{PressureObserver}} object has the following internal slots:

For the [=rate obfuscation=] mitigation the constructed {{PressureObserver}} object additionally has the following internal slots:

Pressure States

Pressure states represents the minimal set of useful states that allows websites to react to changes in compute and system pressure with minimal degration in quality or service, or user experience.

    enum PressureState { "nominal", "fair", "serious", "critical" };
  

The PressureState enum represents the [=pressure state=] with the following states:

Contributing Factors

Contributing factors represent the underlying hardware metrics contributing to the [=current pressure state=] and can be [=implementation-defined=].

The adjusted pressure state is a [=pressure state=] determined by an [=implementation-defined=] algorithm that takes as input [=source type=] and any other [=implementation-defined=] data from [=contributing factors=]. This algorithm MUST not be deterministic to ensure [=break calibration=] mitigation effectiveness.

The change in contributing factors is substantial steps are as follows:

  1. If [=implementation-defined=] low-level hardware metrics that contribute to the [=current pressure state=] drop below or exceed an, per metric, [=implementation-defined=] threshold for the [=current pressure state=], return true.
  2. Return false.

Pressure Observer

The Compute Pressure API enables developers to understand the pressure of system resources such as the CPU.

The PressureUpdateCallback callback

    callback PressureUpdateCallback = undefined (
      sequence<PressureRecord> changes,
      PressureObserver observer
    );
  
This callback will be invoked when the [=pressure state=] changes.

The PressureObserver object

The {{PressureObserver}} can be used to observe changes in the [=pressure states=].

    [Exposed=(DedicatedWorker,SharedWorker,Window), SecureContext]
    interface PressureObserver {
      constructor(PressureUpdateCallback callback);

      Promise<undefined> observe(PressureSource source, optional PressureObserverOptions options = {});
      undefined unobserve(PressureSource source);
      undefined disconnect();
      sequence<PressureRecord> takeRecords();

      [SameObject] static readonly attribute FrozenArray<PressureSource> knownSources;
    };
  

The PressureObserver interface represents a {{PressureObserver}}.

The constructor() method

The `new` {{PressureObserver(callback)}} constructor steps are:

  1. Set |this|.{{PressureObserver/[[Callback]]}} to |callback:PressureUpdateCallback|.

The observe() method

The {{PressureObserver/observe(source, options)}} method steps are:

  1. Let |relevantGlobal| be [=this=]'s [=relevant global object=].
  2. [=list/For each=] |document:Document| in |relevantGlobal|'s [=owning document set=]:
    1. If |document| is not [=allowed to use=] the [=policy-controlled feature=] token "compute-pressure", return [=a promise rejected with=] {{NotAllowedError}}.
  3. Set [=this=].{{PressureObserver/[[SampleIntervalMap]]}}[|source|] to |options:PressureObserverOptions|'s {{PressureObserverOptions/sampleInterval}}.
  4. Let |promise:Promise| be [=a new promise=].
  5. Let |pendingPromiseTuple| be (|source|, |promise|).
  6. [=list/Append=] |pendingPromiseTuple| to [=this=].{{PressureObserver/[[PendingObservePromises]]}}.
  7. [=promise/React=] to |promise|:
    • If |promise| was [=resolved|fulfilled=] or [=rejected=], then:
      1. [=list/Remove=] |tuple| from [=this=].{{PressureObserver/[[PendingObservePromises]]}}.
  8. Run the following steps [=in parallel=]:
    1. Let |platformCollector| be null.
    2. If |relevantGlobal|'s [=platform collector mapping=] [=map/contains=] |source|:
      1. Set |platformCollector| to |relevantGlobal|'s [=platform collector mapping=][|source|].
    3. Otherwise:
      1. Let |newCollector| be a new [=platform collector=] whose [=platform collector/associated pressure source=] is null.
      2. Let |virtualPressureSource:virtual pressure source or null| be the result of invoking [=get a virtual pressure source=] with |source| and |relevantGlobal|.
      3. If |virtualPressureSource| is not null:
        1. If |virtualPressureSource|'s [=virtual pressure source/can provide samples=] is true:
          1. Set |newCollector|'s [=platform collector/associated pressure source=] to |virtualPressureSource|.
          2. [=set/Append=] |newCollector| to |virtualPressureSource|'s [=virtual pressure source/connected platform collectors=].
      4. Otherwise:
        1. Let |realPressureSource| be an [=implementation-defined=] [=pressure source=] that provides telemetry data about |source|, or null if none exists.
        2. Set |newCollector|'s [=platform collector/associated pressure source=] to |realPressureSource|.
      5. If |newCollector|'s [=platform collector/associated pressure source=] is not null:
        1. Set |platformCollector| to |newCollector|.
        2. Set |relevantGlobal|'s [=platform collector mapping=][|source|] to |platformCollector|.
    4. If |platformCollector| is null, [=queue a global task=] on the [=PressureObserver task source=] given |relevantGlobal| to reject |promise| {{NotSupportedError}} and abort these steps.
    5. Invoke [=activate data collection=] with |source| and |relevantGlobal|.
    6. [=Queue a global task=] on the [=PressureObserver task source=] given |relevantGlobal| to run these steps:
      1. If |promise| was rejected, run the following substeps:
        1. If |relevantGlobal|'s [=registered observer list=] for |source| is [=list/empty=], invoke [=deactivate data collection=] with |source| and |relevantGlobal|.
        2. Return.
      2. [=list/Append=] a new [=registered observer=] whose [=observer=] is [=this=] to |relevantGlobal|'s [=registered observer list=] for |source|.
      3. Resolve |promise|.
  9. Return |promise|.

The unobserve() method

The {{PressureObserver/unobserve(source)}} method steps are:

  1. If |source:PressureSource| is not a [=supported source type=], throw {{"NotSupportedError"}}.
  2. [=list/Remove=] from |this|.{{PressureObserver/[[QueuedRecords]]}} all |records| associated with |source|.
  3. [=map/Remove=] |this|.{{PressureObserver/[[SampleIntervalMap]]}}[|source|].
  4. [=map/Remove=] |this|.{{PressureObserver/[[LastRecordMap]]}}[|source|].
  5. [=map/Remove=] |this|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}[|source|].
  6. [=list/For each=] (|promiseSource|, |pendingPromise|) of [=this=].{{PressureObserver/[[PendingObservePromises]]}}, if |source| is equal to |promiseSource|, [=reject=] |pendingPromise| with an {{AbortError}}.
  7. Let |relevantGlobal| be [=this=]'s [=relevant global object=].
  8. Let |registeredObserverList| be |relevantGlobal|'s [=registered observer list=] for |source|.
  9. [=list/Remove=] any [=registered observer=] from |registeredObserverList| whose [=observer=] is [=this=].
  10. If |registeredObserverList| is [=list/empty=]:
    1. Invoke [=deactivate data collection=] with |source| and |relevantGlobal|.
    2. [=map/Remove=] |relevantGlobal|'s [=platform collector mapping=][|source|].

The disconnect() method

The {{PressureObserver/disconnect()}} method steps are:

  1. [=list/Empty=] |observer|.{{PressureObserver/[[QueuedRecords]]}}.
  2. [=map/Clear=] |this|.{{PressureObserver/[[SampleIntervalMap]]}}.
  3. [=map/Clear=] |this|.{{PressureObserver/[[LastRecordMap]]}}.
  4. [=map/Clear=] |this|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}.
  5. [=list/For each=] (|promiseSource|, |pendingPromise|) of [=this=].{{PressureObserver/[[PendingObservePromises]]}}, [=reject=] |pendingPromise| with an {{AbortError}}.
  6. Let |relevantGlobal| be [=this=]'s [=relevant global object=].
  7. [=map/For each=] |source| → |registeredObserverList| of |relevantGlobal|'s [=registered observer list=] [=ordered map=]:
    1. [=list/Remove=] any [=registered observer=] from |registeredObserverList| whose [=observer=] is [=this=].
    2. If |registeredObserverList| is [=list/empty=]:
      1. Invoke [=deactivate data collection=] with |source| and |relevantGlobal|.
      2. [=map/Remove=] |relevantGlobal|'s [=platform collector mapping=][|source|].

The takeRecords() method

The {{PressureObserver/takeRecords()}} method steps are:

  1. Let |records| be a [=list/clone=] of |observer|.{{PressureObserver/[[QueuedRecords]]}}.
  2. [=list/Empty=] |observer|.{{PressureObserver/[[QueuedRecords]]}}.
  3. Return |records|.

The knownSources attribute

The {{PressureObserver/knownSources}} getter steps are:

  1. Return [=user agent=]'s [=supported source types=] in alphabetical order.

The PressureRecord interface

    [Exposed=(DedicatedWorker,SharedWorker,Window), SecureContext]
    interface PressureRecord {
      readonly attribute PressureSource source;
      readonly attribute PressureState state;
      readonly attribute DOMHighResTimeStamp time;
      [Default] object toJSON();
    };
  

A constructed {{PressureRecord}} object has the following internal slots:

The source attribute

The {{PressureRecord/source}} [=getter steps=] are to return its {{PressureRecord/[[Source]]}} internal slot.

The state attribute

The {{PressureRecord/state}} [=getter steps=] are to return its {{PressureRecord/[[State]]}} internal slot.

The time attribute

The {{PressureRecord/time}} [=getter steps=] are to return its {{PressureRecord/[[Time]]}} internal slot.

The toJSON member

When {{PressureRecord.toJSON}} is called, run [[[WebIDL]]]'s [=default toJSON steps=].

The PressureObserverOptions dictionary

    dictionary PressureObserverOptions {
      [EnforceRange] unsigned long sampleInterval = 0;
    };
  

The sampleInterval member

The {{PressureObserverOptions/sampleInterval}} member represents the [=requested sampling interval=] expressed in milliseconds.

Life-cycle and garbage collection

Each [=global object=] has a strong reference to [=registered observers=] in their [=registered observer list=] (one per source).

Processing Model

This section outlines the steps the user agent must take when implementing the specification.

Supporting algorithms

The reset observation window steps given the argument |observer:PressureObserver|, are as follows:

  • set |observer|.{{PressureObserver/[[ObservationWindow]]}} to an [=implementation-defined=] randomized integer value in milliseconds within an [=implementation-defined=] range.
  • set |observer|.{{PressureObserver/[[MaxChangesThreshold]]}} to an [=implementation-defined=] randomized integer value of maximum allowed changes within the |observationWindow| within an [=implementation-defined=] range.
  • set |observer|.{{PressureObserver/[[PenaltyDuration]]}} to an [=implementation-defined=] randomized integer value in milliseconds, within an [=implementation-defined=] range.
  • [=list/Empty=] the observer.{{PressureObserver/[[ChangesCountMap]]}} map.
Run the [=reset observation window=] steps and start a timer to re-run the steps when the observer.{{PressureObserver/[[ObservationWindow]]}} time has passed, using different randomized values.

To determine the owning document set for a [=relevant global object=] |relevantGlobal|:

  1. Let |owningDocumentSet| be an empty [=set=].
  2. If |relevantGlobal| is {{Window}}, then [=set/append=] |relevantGlobal|'s [=associated document=] to |owningDocumentSet|.
  3. Otherwise, [=list/for each=] |owner| in {{WorkerGlobalScope}} |relevantGlobal|'s [=WorkerGlobalScope/owner set=]:
    1. If |owner| is a {{Document}}, then [=set/append=] |owner| to |owningDocumentSet|.
    2. If |owner| is a {{WorkerGlobalScope}}, set |owningDocumentSet| to the [=set/union=] of |owningDocumentSet| and |owner|'s [=owning document set=].
  4. Return |owningDocumentSet|.

The document has implicit focus steps given the argument |document:Document|, are as follows:

  1. If |document| is not [=Document/fully active=], return false.
  2. Let |relevantGlobal| be |document|'s [=relevant global object=].
  3. [=list/For each=] |origin| in initiators of active Picture-in-Picture sessions:
    1. If |relevantGlobal|'s [=relevant settings object=]'s [=origin=] is [=same origin=] with |origin|, return true.
  4. If |relevantGlobal|'s [=browsing context=] is [=context is capturing|capturing=], return true.
  5. Let |topLevelBC| be |relevantGlobal|'s [=browsing context=]'s [=top-level browsing context=].
  6. If |topLevelBC| does not have [=top-level traversable/system focus=], return false.
  7. Let |focusedDocument| be the |topLevelBC|'s currently focused area's [=Node/node document=].
  8. If |relevantGlobal|'s [=relevant settings object=]'s [=origin=] is [=same origin=] with |focusedDocument|'s [=origin=], return true.
  9. Otherwise, return false.

The may receive data steps given the argument |observer:PressureObserver| are as follows:

  1. Let |relevantGlobal| be |observer|'s [=relevant global object=].
  2. If |relevantGlobal| is a {{Window}} object:
    1. Return the result of running [=document has implicit focus=] with |relevantGlobal|'s [=associated Document=].
  3. If |relevantGlobal| is a {{WorkerGlobalScope}} object:
    1. Let |owningDocuments| be |relevantGlobal|'s [=owning document set=].
    2. [=list/For each=] |document| in |owningDocuments|:
      1. If the result of running [=document has implicit focus=] with |document| is true, return true.
      2. Otherwise, [=iteration/continue=].
  4. Return false.

The passes rate test steps given the argument |observer:PressureObserver|, |source:PressureSource| and |timestamp:DOMHighResTimeStamp|, are as follows:
  1. If |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|] does not [=map/exist=], return true.
  2. Let |record:PressureRecord| be |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|].
  3. Let |sampleInterval| be |observer|.{{PressureObserver/[[SampleIntervalMap]]}}[|source|].
  4. Let |timeDeltaMilliseconds:DOMHighResTimeStamp| = |timestamp| - |record|.{{PressureRecord/[[Time]]}}.
  5. If |timeDeltaMilliseconds| ≥ |sampleInterval|, return true, otherwise return false.
The has change in data steps given the argument |observer:PressureObserver|, |source:PressureSource|, |state:PressureState|, are as follows:
  1. If |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|] does not [=map/exist=], return true.
  2. Let |record:PressureRecord| be |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|].
  3. If |record|.{{PressureRecord/[[State]]}} is not equal to |state| and [=change in contributing factors is substantial=] returns true, return true.
  4. Return false.
The passes rate obfuscation test steps given the argument |observer:PressureObserver|, |source:PressureSource|, are as follows:
  1. Increment observer.{{PressureObserver/[[ChangesCountMap]]}}[|source|].
  2. Return observer.{{PressureObserver/[[ChangesCountMap]]}}[|source|] ≤ observer.{{PressureObserver/[[MaxChangesThreshold]]}}.

To get a virtual pressure source, given a [=source type=] |source| and |relevantGlobal|, perform the following steps. They return a [=virtual pressure source=] or null.

  1. Let |topLevelTraversable| be null.
  2. If |relevantGlobal| is a {{Window}} object:
    1. Set |topLevelTraversable| to |relevantGlobal|'s [=Window/navigable=]'s [=top-level traversable=].
  3. If |relevantGlobal| is a {{DedicatedWorkerGlobalScope}} object:
    1. Let |owningDocuments| be |relevantGlobal|'s [=owning document set=].
    2. If |owningDocuments| is [=set/empty=], return null.
    3. [=Assert=]: |owningDocuments|'s [=set/size=] is 1.
    4. Set |topLevelTraversable| to |owningDocuments|[0]'s [=node navigable=]'s [=top-level traversable=].
  4. If |topLevelTraversable| is null, return null.
  5. Let |topLevelVirtualPressureSourceMapping| be the |topLevelTraversable|'s [=virtual pressure source mapping=].
  6. Let |virtualPressureSource| be null.
  7. If |topLevelVirtualPressureSourceMapping| [=map/contains=] |source|:
    1. Set |virtualPressureSource| to |topLevelVirtualPressureSourceMapping|[|source|].
  8. Return |virtualPressureSource|.

Data Collection and Delivery

To activate data collection given a [=source type=] |source| and |relevantGlobal|, perform the following steps:

  1. If |relevantGlobal|'s [=platform collector mapping=] does not [=map/contain=] |source|, abort these steps.
  2. Let |platformCollector| be |relevantGlobal|'s [=platform collector mapping=][|source|].
  3. If |platformCollector|'s [=platform collector/activated=] is true, abort these steps.
  4. Set |platformCollector|'s [=platform collector/activated=] to true.
  5. In an [=implementation-defined=] manner, start running the [=data collection=] steps with |relevantGlobal|, |source|, and |platformCollector|.

To deactivate data collection given a [=source type=] |source| and |relevantGlobal|, perform the following steps:

  1. If |relevantGlobal|'s [=platform collector mapping=] does not [=map/contain=] |source|, abort these steps.
  2. Let |platformCollector| be |relevantGlobal|'s [=platform collector mapping=][|source|].
  3. If |platformCollector|'s [=platform collector/activated=] is false, abort these steps.
  4. In an [=implementation-defined=] manner, stop running the [=data collection=] steps with |relevantGlobal|, |source|, and |platformCollector|.
  5. Set |platformCollector|'s [=platform collector/activated=] to false.
  6. If |platformCollector|'s [=platform collector/associated pressure source=] is a [=virtual pressure source=]:
    1. [=set/Remove=] |platformCollector| from its [=platform collector/associated pressure source=]'s [=virtual pressure source/connected platform collectors=].
  7. Otherwise, perform any [=implementation-defined=] steps to signal to |platformCollector|'s [=platform collector/associated pressure source=] to stop retrieving telemetry data.

The data collection steps given |relevantGlobal|, |source| and |platformCollector| are as follows:

  1. Let |pressureSource| be |platformCollector|'s [=platform collector/associated pressure source=].
  2. If |pressureSource| is null, abort these steps.
  3. Let |sample| be |pressureSource|'s [=pressure source/latest sample=].
  4. If |sample| is null, abort these steps.
  5. Let |state:PressureState| be null.
  6. If |pressureSource| is a [=virtual pressure source=]:
    1. Set |state| to |sample|'s [=pressure source sample/data=].
  7. Otherwise:
    1. Set |state| to an [=adjusted pressure state=] calculated from |source| and |sample|'s [=pressure source sample/data=].
  8. [=Assert=]: |state| is not null.
  9. Let |rawTimestamp| be |sample|'s [=pressure source sample/timestamp=].
  10. Let |timeValue| be the [=relative high resolution time=] based on |rawTimestamp| and |relevantGlobal|.
  11. [=list/For each=] |observer:PressureObserver| in |relevantGlobal|'s [=registered observer list=] for |source|:
    1. If running [=may receive data=] with |observer| returns false, [=iteration/continue=].
    2. If running [=passes rate test=] with |observer|, |source| and |timeValue| returns false, [=iteration/continue=].
    3. If running [=has change in data=] with |observer|, |source| and |state| returns false, [=iteration/continue=].
    4. Let |record:PressureRecord| be a new {{PressureRecord}} object with its {{PressureRecord/[[Source]]}} set to |source|, {{PressureRecord/[[State]]}} set to |state| and {{PressureRecord/[[Time]]}} set to |timeValue|.
    5. If |observer|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}[source] [=map/exists=]:
      1. Set |observer|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}[|source|] to |record|.
      2. [=iteration/Continue=].
    6. If running [=passes rate obfuscation test=] with |observer| and |source| returns false:
      1. Set |observer|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}[|source|] to |record|.
      2. Set |observer|.{{PressureObserver/[[ChangesCountMap]]}}[|source|] to 0.
      3. Create timer of |observer|.{{PressureObserver/[[PenaltyDuration]]}} duration with the following callback:
        1. If |observer|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}[source] [=map/exists=]:
          1. Let |record| be |observer|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}[|source|].
          2. [=map/Remove=] |observer|.{{PressureObserver/[[AfterPenaltyRecordMap]]}}[|source|].
          3. Run [=queue a record=] with |observer|, |source|, |record|.
      4. [=iteration/Continue=].
    7. Run [=queue a record=] with |observer|, |source|, |record|.

Queue a PressureRecord

To queue a record given the arguments |observer:PressureObserver|, |source:PressureSource|, |record:PressureRecord|, run these steps:

  1. If [=list/size=] of |observer|.{{PressureObserver/[[QueuedRecords]]}} is greater than [=max queued records=], then [=list/remove=] the first [=list/item=].
  2. [=list/Append=] |record| to |observer|.{{PressureObserver/[[QueuedRecords]]}}.
  3. Set |observer|.{{PressureObserver/[[LastRecordMap]]}}[|source|] to |record|.
  4. [=Queue a pressure observer task=] with |observer|'s [=relevant global object=].

Queue a Pressure Observer Task

The PressureObserver task source is a [=task source=] used for scheduling tasks to [[[#notify-observers]]].

To queue a pressure observer task given |relevantGlobal| as input, run these steps:

  1. If the |relevantGlobal|'s [=pressure observer task queued=] is true, then return.
  2. Set the |relevantGlobal|'s [=pressure observer task queued=] to true.
  3. [=Queue a global task=] on [=PressureObserver task source=] with |relevantGlobal| to [=notify pressure observers=].

Notify Pressure Observers

To notify pressure observers given |relevantGlobal| as input, run these steps:

  1. Set |relevantGlobal|'s [=pressure observer task queued=] to false.
  2. Let |notifySet| be a new [=set=] of all [=observers=] in |relevantGlobal|’s [=registered observer lists=].
  3. [=list/For each=] |observer:PressureObserver| of |notifySet|:
    1. Let |records| be a [=list/clone=] of |observer|.{{PressureObserver/[[QueuedRecords]]}}.
    2. [=list/Empty=] |observer|.{{PressureObserver/[[QueuedRecords]]}}.
    3. If |records| is not [=list/empty=], then invoke |observer|.{{PressureObserver/[[Callback]]}} with |records| and |observer|. If this throws an exception, catch it, and [=report the exception=].

Handling change of [=Document/fully active=] status

This specification defines the following [=unloading document cleanup steps=] given a {{Document}} |document|:

  1. Let |relevantGlobal| be |document:Document|'s [=relevant global object=].
  2. [=list/For each=] |source| [=map/key=] of |relevantGlobal|'s [=registered observer list=] [=ordered map=]:
    1. Invoke [=deactivate data collection=] with |source| and |relevantGlobal|.
    2. [=map/Remove=] |relevantGlobal|'s [=platform collector mapping=][|source|].

This specification previously included steps covering the case of a {{Document}} becoming [=Document/fully active=] again (i.e. integration with {{Document}}'s [=Document/reactivate=] steps). Those steps have been removed while the intended behavior is discussed.

Handling changes to worker status

Whenever a {{WorkerGlobalScope}} |relevantGlobal|'s [=WorkerGlobalScope/closing=] flag is set to true, perform the following steps:

  1. [=list/For each=] |source| [=map/key=] of |relevantGlobal|'s [=registered observer list=] [=ordered map=]:
    1. Invoke [=deactivate data collection=] with |source| and |relevantGlobal|.
    2. [=map/Remove=] |relevantGlobal|'s [=platform collector mapping=][|source|].

Security and privacy considerations

Types of privacy and security threats

The Working Group will list any known attack vectors, both theoretical and real-world, in this section.

Timing attacks

It may be possible to identify users across non-[=same origin=] sites if unique or very precise values can be accessed at the same time by sites not sharing origin. This attack is mitigated by [[[#data-minimization]]], [[[#rate-limiting-change-notifications]]], and [[[#same-origin-restriction]]].

Cross-site covert channel

In computer security a covert channel creates a capability to transfer information between processes that are not supposed to be allowed to communicate. In modern multi-process web engines in the generic case each window or tab resides in its own process (documents that have the [=same origin=] or sites that have the [=same site=] typically share the same process). Using this API it may be possible to create a cross-site covert channel C where a site A on one tab first broadcasts to the channel C after having manipulated the state of the CPU. Next a site B (that is not same site with site A) on another tab reads the broadcasted data from the channel C by using this API to learn when the state of the CPU has changed. This process is repeated as long as the scripts run on both the sites A and B.

This attack is mitigated by [[[#rate-limiting-change-notifications]]], [[[#rate-obfuscation]]] and [[[#break-calibration]]]. Implementers are advised to consider all these mitigations for long-running scripts.

The longer the scripts run the more information can be transmitted using the proposed cross-site covert channel. For example, if a user is on a video conferencing site and another long-running site that allows for more information to be transferred compared to a regular browsing scenario. On the other hand, a workload such as a video conferencing session will typically exert sustained pressure on the CPU that makes it harder to manipulate the pressure state in a predictive manner.

Targeted de-anonymization attacks

Targeted de-anonymization attacks constitute a critical class of threats that jeopardize a user's anonymity. These attacks allow a malicious or partially compromised website (referred to as the “malicious site”) to ascertain whether a website visitor possesses a specific public identifier, such as an email address or a social media handle.

While anonymity may be a luxury for some, for certain individuals, it is far more than that—it is a matter of survival. Consider for instance those who engage in political protests, work as journalists covering sensitive topics, etc.

As an example, an attacker can privately share a resource with the target for instance using a public resource sharing service (“victim site”), and then measure side-effects (indicating successful access) on loading the resource via side-channels. If the logged in visitor can access the embedded resource successfully, that indicates that the current visit is indeed the intended target.

Specifically, exposing reliable information about the total CPU pressure can let an attacking site understand if a target of a cross-origin navigation (e.g. an iframe or pop-up window from another site) performed a CPU-intensive operation.

Techniques such as pop-under and tab-under can be used to hide the loading from the user.

One possible attack is that the malicious website opens e.g., a popup to a resource on a victim site to which the user is logged in (e.g. a video streaming site or online document editor) pointing to a resource shared with specific users.

Assuming that loading the resource puts increased pressure on the CPU, this would create a side-channel reveals to the attacking site if the user is logged into an account with access to the resource, deanonymizing the user.

Given that modern CPUs recover quickly from high pressure, one possible mitigation strategy could be to temporarily disable readings for a few seconds after loading popup and iframe content.

Mitigation strategies

This section gives a high-level view into mitigation strategies applicable to this specification. The normative definitions of these mitigations are integrated into the respective algorithms of this specification. Implementers are advised to consider the TAG guidance on private browsing modes when implementing the mitigations defined in this specification.

Data minimization

This specification adheres to the generic data minimization principles to limit exposure of data related to low-level details of the underlying platform to the minimum required to address its high-value use cases. This includes consideration for limiting exposure of identifying information about devices.

The specific application of data minimization principles in the context of this specification are discussed in [[[#rate-limiting-change-notifications]]] and [[[#same-origin-restriction]]].

Rate-limiting change notifications

By rate-limiting the delivery of the pressure state information we remove the attacker's ability to observe the precise time when a value transitions between two states.

More precisely, once the pressure observer is activated, it will be called once with initial values, and then is called when the values change. The subsequent calls will be rate-limited. When the callback is called, the most recent value is reported.

The specification will recommend a rate limit of at most one call per second for the active window, and one call per 10 seconds for all other windows. We will also recommend that the call timings are jittered across origins.

These measures benefit the user's privacy, by reducing the risk of identifying a device across multiple origins. The rate-limiting also benefits the user's security, by making it difficult to use this API for timing attacks. Last, rate-limiting change callbacks places an upper bound on the performance overhead of this API.

Rate limiting can be implemented in the user agent, but it might also be possible to simply change the polling/sampling rate of the underlying hardware counters, if not accessed via a higher level framework.

Rate obfuscation

The specification requires implementing the rate obfuscation mitigation to keep track of the number of pressure changes over an [=implementation-defined=] sliding observation window and set a flag if an [=implementation-defined=] threshold for the number of pressure changes is exceeded. Similarly, it is also recommended for the implementation to observe any abnormal activity such as a high number of pressure state changes spanning across multiple states, and set this flag similarly.

If this flag is set, the implementation is recommended to give the pressure observer a penalty during which it will not be able to inform scripts of changes in its pressure state as it normally would. The duration of this penalty is [=implementation-defined=] and it is recommended to be randomized. When [=notify pressure observers=] resumes operation after the penalty, it only reports the latest pressure state and disregards any interim state information received from the platform collector during this penalty.

Rate obfuscation normative parameters

Based on implementation experience, implementers must use:

  • a range in between 50 and 100 changes for PressureObserver's {{PressureObserver/[[MaxChangesThreshold]]}} internal slot.
  • a range in between 5000 milliseconds and 10000 milliseconds for PressureObserver's {{PressureObserver/[[PenaltyDuration]]}} internal slot.

Rate obfuscation non-normative parameters

This section is non-normative.

Based on implementation experience, implementers are advised to use:

  • a range in between 300000 milliseconds (5 minutes) and 600000 milliseconds (10 minutes) for PressureObserver's {{PressureObserver/[[ObservationWindow]]}} internal slot.

Break calibration

In a calibration process an attacker tries to manipulate the CPU so that this API would report a transition into a certain pressure state with the highest probability in response to the pressure exerted by the fabricated workload. This break calibration mitigation solution can slow down or prevent this calibration process from succeeding by slightly changing at runtime the [=implementation-defined=] low-level hardware metrics that contribute to these pressure state transitions. Even if the initial calibration would succeed, its results will be invalidated at runtime when this mitigation is running continuously. Any attempts to recalibrate will similarly be mitigated against.

Break calibration parameters

This section is non-normative.

Based on implementation experience, implementers are advised to apply the mitigation to a randomized time value within a range between 120000 milliseconds (2 minutes) and 240000 milliseconds (4 minutes).

Same-origin restriction

By default data delivery is restricted to documents served from the same-origin as an initiator of an active picture-in-picture-session, documents [=context is capturing|capturing=] or the document with [=top-level traversable/system focus=], if any.

The documents qualifying for data delivery, under the above rules, can delegate it to documents in [=child navigables=].

The feature can be extended to third-party contexts such as iframes only by a declared policy.

Shared workers can be shared across documents, such as top level document and those associated iframes. If one of the documents in the [=WorkerGlobalScope/owner set=] passes the above data delivery requirements, the shared worker will qualify for data delivery. This means that the embedded iframe is able to pass along the data to the embedding document.

Accessibility considerations

The Compute Pressure API is focused on improving the user experience. There are two ways in which applications that build on the API can positively impact accessibility.

  1. Considering users' access needs when making decisions based on information gathered using the API.
  2. Designing and making user interfaces based on information gained from the API with accessibility in mind.

As a consumer of the API, it's important to consider both of these opportunities. Here are some examples:

Automation

The Compute Pressure API poses a challenge to test authors, as fully exercising interface requires physical hardware devices that respond in predictable ways.

To address this challenge this document defines a [[!WEBDRIVER2]] [=extension commands=] that allows defining and controlling virtual pressure sources that behave like real ones and which can have particular properties and whose readings can be entirely defined by users.

Virtual Pressure Source

A virtual pressure source is a [=pressure source=] that simulates the behavior of a real one in controlled ways. It reports pressure changes to zero or more [=platform collectors=] connected to it.

Contrary to a real [=pressure source=], however, it reports [=pressure state=] values directly instead of [=implementation-defined=] values that must be processed into [=pressure states=] by a [=platform collector=]. In other words, a [=virtual pressure source=]'s [=pressure source sample=]'s [=pressure source sample/data=] is a {{PressureState}}.

In addition to the data associated with all [=pressure sources=] (such as [=pressure source sample=]), each [=virtual pressure source=] has:

Each [=top-level traversable=] has a virtual pressure source mapping, which is an [=ordered map=] of [=source types=] to [=virtual pressure source=].

Extension Commands

Create virtual pressure source

HTTP Method [=extension command URI Template|URI Template=]
POST /session/{session id}/pressuresource

This [=extension command=] creates a new [=virtual pressure source=] of a specified [=source type=]. Calls to {{PressureObserver/observe()}} from {{PressureObserver}} instances of the same [=source type=] will cause this [=virtual pressure source=] to be used as their backing [=pressure source=] until [[[#delete-virtual-pressure-source]]] is run.

Properties of the parameters argument used by this algorithm
Parameter name Value type Required
type String yes
supported Boolean no

The [=remote end steps=] given |session|, |URL variables| and |parameters| are:

  1. Let |virtualPressureSourceType| be the result of invoking get a property "type" from |parameters|.
  2. If the [=user agent=]'s [=supported source types=] does not [=list/contain=] |virtualPressureSourceType|, return [=error=] with [=error code|WebDriver error code=] [=invalid argument=].
  3. Let |topLevelTraversable| be the current browsing context's [=browsing context/top-level traversable=].
  4. Let |topLevelVirtualPressureSourceMapping| be the |topLevelTraversable|'s [=virtual pressure source mapping=].
  5. If |topLevelVirtualPressureSourceMapping| contains |virtualPressureSourceType|, return [=error=] with [=error code|WebDriver error code=] [=invalid argument=].
  6. Let |supported| be the result of invoking get a property with default with "supported" and true from |parameters|.
  7. Let |virtualPressureSource| be a new [=virtual pressure source=].
  8. Set |virtualPressureSource|'s [=virtual pressure source/can provide samples=] to |supported|.
  9. Set |topLevelVirtualPressureSourceMapping|[|virtualPressureSourceType|] to |virtualPressureSource|.
  10. Return [=success=] with data null.

Delete virtual pressure source

HTTP Method [=extension command URI Template|URI Template=]
DELETE /session/{session id}/pressuresource/{type}

This [=extension command=] deletes a given [=virtual pressure source=], meaning that, if available, data for the given [=source type=] will be delivered the regular way, by non-virtual means.

The [=remote end steps=] given |session|, |URL variables| and |parameters| are:

  1. Let |virtualPressureSourceType| be the value of the |URL variables|["type"].
  2. If the [=user agent=]'s [=supported source types=] does not [=list/contain=] |virtualPressureSourceType|, return [=error=] with [=error code|WebDriver error code=] [=invalid argument=].
  3. Let |topLevelTraversable| be the current browsing context's [=browsing context/top-level traversable=].
  4. Let |topLevelVirtualPressureSourceMapping| be the |topLevelTraversable|'s [=virtual pressure source mapping=].
  5. Let |pressureSource| be |topLevelVirtualPressureSourceMapping|[|virtualPressureSourceType|].
  6. [=set/For each=] |platformCollector| of |pressureSource|'s [=virtual pressure source/connected platform collectors=]:
    1. Set |platformCollector|'s [=platform collector/associated pressure source=] to null.
  7. [=map/Remove=] |topLevelVirtualPressureSourceMapping|[|virtualPressureSourceType|].
  8. Return [=success=] with data null.

Update virtual pressure source

HTTP Method [=extension command URI Template|URI Template=]
POST /session/{session id}/pressuresource/{type}

This [=extension command=] allows updating the state of a [=virtual pressure source=] by pushing a new [=pressure source sample=].

Properties of the parameters argument used by this algorithm
Parameter name Value type Required
sample {{PressureState}} yes

The [=remote end steps=] given |session|, |URL variables| and |parameters| are:

  1. Let |virtualPressureSourceType| be the value of the |URL variables|["type"].
  2. If the [=user agent=]'s [=supported source types=] does not [=list/contain=] |virtualPressureSourceType|, return [=error=] with [=error code|WebDriver error code=] [=invalid argument=].
  3. Let |topLevelTraversable| be the current browsing context's [=browsing context/top-level traversable=].
  4. Let |topLevelVirtualPressureSourceMapping| be the |topLevelTraversable|'s [=virtual pressure source mapping=].
  5. If |topLevelVirtualPressureSourceMapping| does not [=map/contain=] |virtualPressureSource|, return [=error=] with [=error code|WebDriver error code=] unsupported operation.
  6. Let |virtualPressureSource| be |topLevelVirtualPressureSourceMapping|[|virtualPressureSourceType|].
  7. Let |sample| be the result of invoking get a property "sample" from |parameters|.
  8. If |sample| is not of type {{PressureState}}, return [=error=] with [=error code|WebDriver error code=] [=invalid argument=].
  9. Set |virtualPressureSource|'s [=pressure source/latest sample=] to a new [=pressure source sample=] whose [=pressure source sample/data=] is |sample| and [=pressure source sample/timestamp=] is the [=unsafe shared current time=].
  10. In an [=implementation-defined=] way, make |virtualPressureSource|'s [=pressure source/latest sample=] available to |virtualPressureSource|'s [=virtual pressure source/connected platform collectors=].
  11. Return [=success=] with data null.

Examples

    const samples = [];

    function pressureChange(records, observer) {
      for (const record of records) {
        samples.push(record.state);

        // We only want 20 samples.
        if (samples.length == 20) {
          observer.disconnect();
          return;
        }
      }
    }

    const observer = new PressureObserver(pressureChange);
    observer.observe("cpu");
  

In the following example we want to lower the number of concurrent video streams when the pressure becomes critical. For the sake of simplicity we only consider this one state.

As lowering the amount of streams might not result in exiting the critical state, or at least not immediately, we use a strategy where we lower one stream at the time every 30 seconds while still in the critical state.

We accomplish this by making sure the callback is called at least once every 30 seconds, or when the state actually changes. When the state changes we reset the interval timer.

    let timerId = -1;
    function pressureChange(records) {
      // Clear timer every time we are called, either by an actual state change,
      // or when called by setTimeout (see below).
      if (timerId > 0) {
        clearTimeout(timerId);
      }

      // When entering critical state, we want to recheck every 30sec if we are
      // still in critical state and if so, further reduce our concurrent streams.
      // For this reason we create a timer for 30 seconds that will call us back
      // with the last result in there were no change.
      const lastRecordArray = [records.at(records.length - 1)];
      timerId = setTimeout(pressureChange.bind(this, lastRecordArray), 30_000);

      for (const record of records) {
        if (record.state == "critical") {
          let streamsCount = getStreamsCount();
          setStreamsCount(streamsCount--);
        }
      }
    }

    const observer = new PressureObserver(pressureChange);
    observer.observe("cpu");
  

In the following example, we want to demonstrate the usage of {{PressureObserver/takeRecords()}}, by retrieving the remaining |records| accumulated since the the callback was last invoked.

It is recommended to do so before {{PressureObserver/disconnect()}}, otherwise {{PressureObserver/disconnect()}} will clear them and they will be lost forever.

For example, we might want to measure the pressure during a benchmarking workload, and thus want pressure telemetry for the exact duration of the workload. This means disconnecting all observers immediately when the task is completed, and manually requesting any pending pressure telemetry up to this point that might not have been delivered yet as part of the event loop cycle.

    function logWorkloadStatistics(records) {
      // do something with records.
    }

    const observer = new PressureObserver(logWorkloadStatistics);
    observer.observe("cpu");

    // Read pending state change records, otherwise they will be cleared
    // when we disconnect.
    const records = observer.takeRecords();
    logWorkloadStatistics(records);

    observer.disconnect();
  

In the following example, we show how to tell the observer to stop watching a specific |source:PressureSource| by invoking {{PressureObserver/unobserve()}} with |source|.

    const observer = new PressureObserver(records => { /* do something with records. */ });

    observer.observe("cpu");
    observer.observe("gpu");

    // Callback now gets called whenever the pressure state changes for 'cpu' or 'gpu'.

    observer.unobserve("gpu");

    // Callback now only gets called whenever the pressure state changes for 'cpu'.
  

In the following example, we show how to tell the observer to stop watching for any state changes by calling {{PressureObserver/disconnect()}}. Calling {{PressureObserver/disconnect()}} will stop observing all sources observed by previous {{PressureObserver/observe()}} calls.

Additionally it will clear all pending records collected since the last callback was invoked.

    const observer = new PressureObserver(records => { // do something with records. });
    observer.observe("cpu");
    observer.observe("gpu");

    // some time later...

    observer.disconnect();

    // records will be an empty array, because of the previous disconnect().
    const records = observer.takeRecords();
  

This specification defines conformance criteria for a single product: a user agent that implements the interfaces that it contains.

Acknowledgments

Many thanks for valuable feedback and advice from Anssi Kostiainen, Asaf Yaffe, Chen Xing, Evan Shrubsole, Florian Scholz, François Beaufort, Jan Gora, Jesse Barnes, Joshua Bell, Kamila Hasanbega, Matt Menke, Moh Haghighat, Nicolás Peña Moreno, Opal Voravootivat, Paul Jensen, Peter Djeu, Reilly Grant, Ulan Degenbaev, Victor Miura, Wei Wang, and Zhenyao Mo

Thanks to the W3C Privacy Interest Group (PING) and especially Peter Snyder for the privacy review, feedback and the proposed cross-site covert channel attack and its mitigations. Similarly thanks to Ehsan Toreini for his work on the privacy of private browsing and related contributions to this specification.

Special thanks to Amanda Zhao, Fidel Tian, Zhiliang Wang and others from the Zoom engineering team for the feedback and hands-on experiments that have helped improve this API in real-world scenarios.