Skip to main content

PORIFERA: Php cOde Rewriting Instrumentation For ExpRession in Ast

Porifera is named for the sponges (phylum Porifera): water streams through their pores and exits unchanged while nutrients are filtered out — here, PHP execution streams through probe-injected pores in the AST and continues unchanged while expression values are filtered out.

PHP AST instrumentation library. Captures runtime values of arbitrary expressions without debuggers or manual logging.

Install

# via uv
uv add porifera

# or via pip
pip install porifera

Requires Python >=3.10.

Usage

from php_parser_py import Parser
import porifera

ast = Parser().parse_file("path/to/project/index.php")

# targets: {ast_node_id: probe_label}
# - key: node ID from php-parser-py AST (e.g. "a1b2c3d4_5")
# - value: label string written to probe output for identification
targets = {
    "a1b2c3d4_5": "user_query",
    "e5f6g7h8_12": "config_value",
}

with porifera.session(targets, ast) as sess:
    for probe in sess.installed:      # targets that received a probe
        print(probe.expr_key, probe.node_id)

    # Run the PHP project (HTTP request or CLI). Probes append to
    # .porifera_data_<timestamp>.jsonl in the project root.

    data = sess.collect()             # {expr_key: ProbeData}
    for key, pd in data.items():
        print(key, pd.values, pd.value_types, pd.timestamps)
# Deinstrument and output cleanup guaranteed on exit

Porifera automatically selects the probe method based on AST context:

Expression Wrap — target is in a safe rvalue position:

// before
$row = $db->query($sql);
// after: wrap the expression inline
$row = __porifera_probe_a1b2("user_query", $db->query($sql));

Statement Probe — target is in a lvalue, reference, or language-construct position:

// before: $x is an assignment target (lvalue)
$x = getPrice();
// after: standalone probe inserted after the statement
$x = getPrice();
__porifera_probe_a1b2("price", $x);
// before: $arr is passed to by-ref function
sort($arr);
// after: probe before the call captures value without breaking reference
__porifera_probe_a1b2("arr", $arr);
sort($arr);

The probe returns the original value transparently and logs it to .porifera_data_<timestamp>.jsonl with fields: key, value, value_type, ts.

Custom write strategy — every write into the project root (instrumented source, require_once injection, runtime helper, backup restore) goes through write_strategy. The default writes a temp file, os.replaces it over the target, and fsyncs the file and parent directory — correct for any ordinary filesystem. Inject your own when the deployment needs different post-write visibility, e.g. an OrbStack bind mount that caches the inode and serves stale bytes to the container after a rename:

import os
from pathlib import Path
import porifera

def same_inode_write(path: Path, content: bytes) -> None:
    # Overwrite in place (no os.replace) so the inode is preserved and the
    # container reads the new bytes immediately.
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
    try:
        os.write(fd, content)
        os.fsync(fd)
    finally:
        os.close(fd)

with porifera.session(targets, ast, write_strategy=same_inode_write) as sess:
    sess.collect()

write_strategy is Callable[[Path, bytes], None] — inject a plain function, no porifera type to import.

API

porifera.session(targets, project_ast, output_dir=None, *, tolerant=False, write_strategy=..., invalidation_trigger=None) — Context manager. Instruments targets on enter, deinstruments on exit. Yields Session. tolerant=True records uninstrumentable targets in skipped instead of raising. write_strategy defaults to the built-in atomic replace. invalidation_trigger runs the opcache invalidation script inside the PHP runtime; None skips invalidation, correct when opcache.validate_timestamps is on.

porifera.Session — installed: list[InstalledProbe], skipped: list[SkippedTarget], modified_files: list[Path], and collect() -> dict[str, ProbeData].

porifera.InstalledProbe — node_id: str, expr_key: str.

porifera.SkippedTarget — node_id: str, expr_key: str, reason: str. Non-empty only with tolerant=True.

porifera.ProbeData — values: list[object], value_types: list[str], timestamps: list[float]. One element per probe invocation.

porifera.recover(root) — Roll back a crashed session's residual snapshot on a root. Recovers only from .porifera_backup/; if the backup is lost while probes remain, the root is not recoverable and this returns [] without raising. Sole standalone restore path — also the defensive cleanup for stale probes from a prior failed run.

porifera.is_declaration_site(ast, node) — True if the node is a name-binding declaration (parameter, closure use, foreach binding, catch variable). Use to filter candidates before building targets.

porifera.InstrumentResult — installed, skipped, modified_files; returned by the layer-1 InstrumentationManager.instrument() for custom lifecycles.

porifera.InstrumentationError / porifera.DeinstrumentationError — Raised on failure.

porifera.WriteStrategy — Callable[[Path, bytes], None]. Type of the write_strategy injection hook; every write into the project root goes through it.

porifera.InvalidationTrigger — Callable[[Path], None]. Type of the invalidation_trigger hook; runs a generated script inside the PHP runtime holding the opcache.

See design.md for full specifications.

Documentation

  • Concepts — problem context, core terminology, data flow
  • Design — class structure, session API, exception types
  • Algorithm — wrap safety classification, statement probe placement
  • Implementation — php-parser-py API, developer notes

For Agents

Agent-consumable documentation index at docs/llms.txt (llmstxt.org format).

Citation

If you use this project in academic work, please cite our paper. BibTeX (placeholder until the paper is released):

@misc{beluga_placeholder,
  title  = {{TODO: paper title — not yet released}},
  author = {{TODO: authors}},
  year   = {{TODO}},
  note   = {Paper not yet released. Citation entry will be updated on publication.}
}

License

GPL-2.0 — see LICENSE.

Metadata

Release files for porifera 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for porifera 0.2.0
File Size Uploaded Provenance Actions
porifera-0.2.0.tar.gz 40.9 kB Without provenance Details for porifera-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for porifera 0.2.0
File Interpreter ABI Platform Actions
porifera-0.2.0-py3-none-any.whl Python 3 none any Details for porifera-0.2.0-py3-none-any.whl

Total release size: 96.9 kB

Release files / porifera-0.2.0.tar.gz

Download URL porifera-0.2.0.tar.gz
Size 40.9 kB
Tags Source
SHA-256 checksum
How to use checksums
8fa351329e26565868f88f0182402c334e62b81ecc3901a9fe6ec0ffbb0ce395
BLAKE2b-256 checksum
How to use checksums
7044985195bd0d1c5ff636beac618865958229cc846afeaeca126e07fddc7bcd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Release files / porifera-0.2.0-py3-none-any.whl

Download URL porifera-0.2.0-py3-none-any.whl
Size 55.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0ea875c9da5ab63a0ca54e34c2549cd106e3b15e138b726b815cb54c5d5b4e47
BLAKE2b-256 checksum
How to use checksums
6fe01e7a7c01e3c06a5d898683da53b771cd7e506be84b1d72ec4d9d3b68e40d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.13

Security for porifera 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page