mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-27 05:05:50 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff4bbbf32b | ||
|
|
7ab9fcf8d1 | ||
|
|
f6079d38fd | ||
|
|
1778044bd8 |
+18
-88
@@ -23,7 +23,7 @@ jobs:
|
||||
matrix:
|
||||
php: ['7.4', '8.3']
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- name: Check syntax and execute PHP regression tests
|
||||
run: |
|
||||
docker run --rm -v "$PWD:/app" -w /app "php:${{ matrix.php }}-cli" sh -ec '
|
||||
@@ -31,37 +31,7 @@ jobs:
|
||||
php tests/php/run.php
|
||||
'
|
||||
|
||||
# Only this job publishes the installable package. No WordPress containers or
|
||||
# downloaded plugins run here, and the artifact is immutable once uploaded.
|
||||
build:
|
||||
name: Build and publish pristine package
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
outputs:
|
||||
package-artifact-id: ${{ steps.package.outputs.artifact-id }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
cache: npm
|
||||
- name: Use the documented npm toolchain
|
||||
run: npm install --global [email protected]
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: npm test
|
||||
- run: npm run package
|
||||
- name: Upload pristine installable ZIP
|
||||
id: package
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: wp-asciiplayer-package-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: dist/wp-asciiplayer.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
wordpress:
|
||||
needs: build
|
||||
name: WordPress ${{ matrix.wordpress }} / PHP ${{ matrix.php }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
@@ -74,20 +44,17 @@ jobs:
|
||||
- wordpress: '6.3'
|
||||
php: '7.4'
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
cache: npm
|
||||
- name: Use the documented npm toolchain
|
||||
run: npm install --global [email protected]
|
||||
- run: npm ci
|
||||
- name: Download the pristine package from this run
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
|
||||
with:
|
||||
artifact-ids: ${{ needs.build.outputs.package-artifact-id }}
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
- run: npm run build
|
||||
- run: npm test
|
||||
- run: npm run package
|
||||
- name: Configure clean WordPress version
|
||||
env:
|
||||
WP_TEST_VERSION: ${{ matrix.wordpress }}
|
||||
@@ -121,14 +88,21 @@ jobs:
|
||||
env:
|
||||
PLAYWRIGHT_HTML_OUTPUT_DIR: playwright-report/i18n
|
||||
run: npm run test:e2e -- --grep @i18n --output=test-results/i18n
|
||||
- name: Run Plugin Check (advisory until directory review)
|
||||
if: always() && matrix.wordpress == 'latest'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
npx --no-install wp-env run cli wp plugin install plugin-check --activate
|
||||
npx --no-install wp-env run cli wp plugin get plugin-check --field=version | tee plugin-check-version.txt
|
||||
npx --no-install wp-env run cli wp plugin check wp-asciiplayer --require=/var/www/html/wp-content/plugins/plugin-check/cli.php --format=json | tee plugin-check-report.txt
|
||||
- name: Record WordPress and PHP logs
|
||||
if: always()
|
||||
run: |
|
||||
npx --no-install wp-env logs --watch=false > wordpress-logs.txt 2>&1 || true
|
||||
npx --no-install wp-env run cli sh -c 'test ! -f wp-content/debug.log || cat wp-content/debug.log' > wordpress-debug.txt 2>&1 || true
|
||||
- name: Upload integration evidence
|
||||
- name: Upload integration evidence and installable ZIP
|
||||
if: always()
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: wordpress-${{ matrix.wordpress }}-php-${{ matrix.php }}
|
||||
if-no-files-found: warn
|
||||
@@ -136,56 +110,12 @@ jobs:
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
plugin-check-version.txt
|
||||
plugin-check-report.txt
|
||||
wordpress-version.txt
|
||||
wordpress-logs.txt
|
||||
wordpress-debug.txt
|
||||
- name: Stop WordPress
|
||||
if: always()
|
||||
run: npx --no-install wp-env stop
|
||||
|
||||
# Plugin Check receives its own disposable copy. It cannot replace the package
|
||||
# uploaded by build, and this job never republishes files from dist.
|
||||
plugin-check:
|
||||
name: Plugin Check (advisory)
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
cache: npm
|
||||
- name: Use the documented npm toolchain
|
||||
run: npm install --global [email protected]
|
||||
- run: npm ci
|
||||
- name: Download the pristine package from this run
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
|
||||
with:
|
||||
artifact-ids: ${{ needs.build.outputs.package-artifact-id }}
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
- name: Start WordPress and install the packaged plugin
|
||||
run: |
|
||||
mkdir -p .wp-env-uploads
|
||||
npx --no-install wp-env start
|
||||
npx --no-install wp-env run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force
|
||||
- name: Run Plugin Check (advisory until directory review)
|
||||
continue-on-error: true
|
||||
run: |
|
||||
npx --no-install wp-env run cli wp plugin install plugin-check --activate
|
||||
npx --no-install wp-env run cli wp plugin get plugin-check --field=version | tee plugin-check-version.txt
|
||||
npx --no-install wp-env run cli wp plugin check wp-asciiplayer --require=/var/www/html/wp-content/plugins/plugin-check/cli.php --format=json | tee plugin-check-report.txt
|
||||
- name: Upload Plugin Check evidence only
|
||||
if: always()
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: plugin-check-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
path: |
|
||||
plugin-check-version.txt
|
||||
plugin-check-report.txt
|
||||
dist/wp-asciiplayer.zip
|
||||
- name: Stop WordPress
|
||||
if: always()
|
||||
run: npx --no-install wp-env stop
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
name: Isolated recording resource-budget experiment
|
||||
on:
|
||||
push:
|
||||
branches: ['experiment/cast-resource-budgets-20261015']
|
||||
paths: ['experiment/**', '.github/workflows/resource-budget-experiment.yml']
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: resource-budget-experiment-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
browser:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
cache: npm
|
||||
- run: npm ci --ignore-scripts
|
||||
- run: npx --no-install playwright install --with-deps chromium
|
||||
- name: Controlled real-browser comparison
|
||||
run: timeout 360s node --max-old-space-size=512 experiment/browser.cjs
|
||||
- name: Retain experiment evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f
|
||||
with:
|
||||
name: resource-budget-browser-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: experiment/results/browser/
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
php:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
php: ['7.4', '8.3']
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Pull official PHP runtime
|
||||
run: docker pull php:${{ matrix.php }}-cli
|
||||
- name: Native PHP controlled comparison
|
||||
run: |
|
||||
mkdir -p experiment/results/php
|
||||
docker image inspect php:${{ matrix.php }}-cli --format '{{json .RepoDigests}}' > experiment/results/php/image-digest.json
|
||||
timeout 240s docker run --rm --network none --memory=512m --cpus=2 --read-only --tmpfs /tmp:rw,size=256m -v "$PWD:/repo:ro" -v "$PWD/experiment/results/php:/results:rw" -w /repo php:${{ matrix.php }}-cli php -d memory_limit=128M experiment/php/run.php /repo /results
|
||||
- name: Retain experiment evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f
|
||||
with:
|
||||
name: resource-budget-php-${{ matrix.php }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: experiment/results/php/
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
@@ -1,55 +0,0 @@
|
||||
# Resource-budget experiment results
|
||||
|
||||
Experiment only. No production implementation, merge, release or deployment.
|
||||
|
||||
## Verified run
|
||||
|
||||
[GitHub Actions run 38667731485](https://github.com/LamGC/wp-asciiplayer/actions/runs/38667731485) passed all three jobs on tested commit `fcaf9be8103214d60485e761858f269d13f55cd7`, based on main `ffff9704e5bca7a07d5f57a2f832475ac102d01c`.
|
||||
|
||||
Runtime versions: Node 24.18.0, Playwright 1.64.0, Chromium 156.0.8078.4, asciinema-player 3.17.0; native PHP 7.4.33 and 8.3.35 in official Docker images. The raw PHP artifacts include the resolved image digests. The player bundle SHA-256 matched `a13c37632e1b5c49fe9128417b9319a9b5bc64cb457dd5ae52cbba8a3aceb880`.
|
||||
|
||||
## Actual browser evidence
|
||||
|
||||
All 31 controlled cases passed, including baseline/prototype v1/v2/v3 playback and seek, top-level and same-origin iframe, marker boundaries, and safe rejection of late resize and excessive terminal cell counts. No dangerous-dimension baseline was rendered.
|
||||
|
||||
| Case | Baseline | Prototype |
|
||||
|---|---:|---:|
|
||||
| 1,000 markers, added DOM elements | 3,049 | 3,049 (accepted) |
|
||||
| 1,001 markers, added DOM elements | 3,052 | 0 (rejected before player creation) |
|
||||
| 3,000 markers, added DOM elements | 9,049 | 0 (rejected before player creation) |
|
||||
| 3,000 markers, initialization / seek | 738.2 ms / 413.2 ms | Rejected in 10.6 ms |
|
||||
|
||||
Zero-marker baseline added 49 elements: the measured differences agree with three additional elements per marker. Baseline 3,000-marker sampled JS heap delta was 4,110,979 bytes; this is not total browser memory or process RSS. Timings are single-run diagnostics on one CI runner, not statistical or mobile performance claims. The protected rejection path made zero player creation calls.
|
||||
|
||||
## Native PHP evidence
|
||||
|
||||
Each measured sample runs in a fresh CLI process with a 128 MiB PHP memory limit and a 20-second watchdog. Values below are PHP tracked peak allocation, not OS RSS.
|
||||
|
||||
| Input | PHP | Baseline peak | Gated peak |
|
||||
|---|---|---:|---:|
|
||||
| 260,000 empty metadata objects, 780,070 bytes | 7.4.33 | 22,122,216 B | 1,255,960 B |
|
||||
| Same | 8.3.35 | 17,927,440 B | 1,247,624 B |
|
||||
| 800,000 metadata scalars, 1,600,070 bytes | 7.4.33 | 35,618,240 B | 2,075,136 B |
|
||||
| Same | 8.3.35 | 18,840,552 B | 2,066,800 B |
|
||||
|
||||
Both rejected shapes stop before json_decode, reducing measured peak allocation by approximately 89–94%. Both versions passed all 229 source-only regression assertions with and without the gate, plus 13 scanner assertions. The earlier local count of 233 included four generated-asset-manifest checks; this source-only CI intentionally did not fabricate build manifests.
|
||||
|
||||
Normal v1, escaped strings and 100,000 simple frames remain accepted. That last case still peaks at 43,763,464 B on PHP 7.4 and 25,666,160 B on PHP 8.3. Preflight adds CPU work: in these native samples the normal 100k-frame check went from 25.4 to 60.7 ms / 38.9 to 76.5 ms, respectively.
|
||||
|
||||
## Confirmed compatibility and remaining work
|
||||
|
||||
The experiment deliberately exposes two compatibility gaps: the original player accepts zero dimensions as defaults and skips blank JSONL lines, while this prototype rejects both. Production integration should preserve safe accepted forms rather than copy the prototype unchanged. Compact single-line v1 and other upstream-tolerated inputs need explicit compatibility decisions.
|
||||
|
||||
Candidate marker limit 1,000, adapter cell budget 40,000, parser/byte/event limits and PHP token budgets are experimental. They are not final recommendations. Per-axis bounds alone still allow an excessive cell product. The browser cell test uses an explicit pre-player adapter seam. Local stream tests established early byte/line rejection; this CI browser harness does not independently reproduce every streaming/network edge case.
|
||||
|
||||
A formal implementation still needs shared upload/playback policy, cancellation on URL changes/disposal, real WordPress editor integration, localization, CORS/credential checks, aggregate multiple-player budgets and low-memory profiling. Same-origin synthetic iframe success is not a full WordPress integration pass. No Cloud finding state was changed.
|
||||
|
||||
## Evidence artifacts
|
||||
|
||||
Artifacts are retained for seven days by this experiment workflow:
|
||||
|
||||
- [Browser raw results](https://github.com/LamGC/wp-asciiplayer/actions/runs/38667731485/artifacts/11942427047)
|
||||
- [Native PHP 7.4 raw results and logs](https://github.com/LamGC/wp-asciiplayer/actions/runs/38667731485/artifacts/11943311264)
|
||||
- [Native PHP 8.3 raw results and logs](https://github.com/LamGC/wp-asciiplayer/actions/runs/38667731485/artifacts/11943136266)
|
||||
|
||||
Conclusion: the tested resource gates demonstrably prevent the intended allocation/rendering paths while preserving the ordinary fixtures. This supports proceeding to a carefully integrated fix after compatibility decisions; it does not establish that the production plugin is already fixed.
|
||||
@@ -1,44 +0,0 @@
|
||||
# Isolated resource-budget experiment, 2026-10-15
|
||||
|
||||
This is experimental evidence, not a production patch or security clearance. No repository source was changed or published; no CI, production system, or external hostile endpoint was exercised.
|
||||
|
||||
## Environment and boundaries
|
||||
|
||||
Node 24.19.0. Installed player 3.17.0 bundle SHA-256 a13c37632e1b5c49fe9128417b9319a9b5bc64cb457dd5ae52cbba8a3aceb880. PHP-WASM 7.4.33 / 8.3.33 via @php-wasm/node 3.1.57. Browser attempted: Chromium 154.0.8037.57, Playwright 1.64.0; blocked before page creation by socket EPERM. No DOM/playback/seek measurement succeeded. No alternate browser bypass attempted.
|
||||
|
||||
Synthetic tests were process-time-limited and Node heaps limited. PHP memory limit 128 MiB, with separate subprocess monitoring. Inputs remain bounded; no intentional host resource exhaustion.
|
||||
|
||||
## Remote loader prototype
|
||||
|
||||
17 baseline loader cases, 8 edge cases, a stalled-reader test, and actual upstream parser compatibility tests pass. Existing hello/replacement/resize/v1-pretty/v3-comments fixtures yield identical events, durations and dimensions through the installed parser and preparation functions. Only the export list in an isolated copy of the upstream core module was changed to expose those functions; this does not execute DOM or terminal rendering.
|
||||
|
||||
A controlled 2,220,037-byte stream baseline fully buffers and parses 20,000 events. With an intentionally small 64-KiB test cap, protected loader cancels after 65,638 bytes and never returns player input. Recorded Node heap delta: baseline 7,166,144 B versus protected 1,796,216 B; 48.15 ms versus 10.30 ms in that single sample. Heap/timing numbers are illustrative, not stable production benchmarks.
|
||||
|
||||
A 300,048-byte event line is rejected before parsing it. Initial dimensions and late resize dimensions above the candidate per-axis limit are rejected. UTF-8 split into single bytes and CRLF work; invalid UTF-8 is rejected. Unknown event codes remain supported. A normal 100,000-output-event cast is accepted. A stalled stream using a 25-ms experimental read deadline was canceled at 30.5 ms.
|
||||
|
||||
## Marker experiment
|
||||
|
||||
Shared preflight accepts 0/100/500/1,000 markers and rejects 1,001/3,000 at marker 1,001. With the actual installed upstream parser/recording preparation, a 3,000-marker baseline retains 3,000 markers; protected loader rejects before calling that parser (zero calls). This validates the pre-player gate. The source-derived three-span-per-marker relationship has NOT been empirically measured in a running browser here.
|
||||
|
||||
## PHP v1 experiment
|
||||
|
||||
PHP tracked peak allocation (not total process RSS):
|
||||
|
||||
- 260k empty metadata objects, 780,070 bytes: PHP 7.4 16,955,544 -> 1,232,192 B; PHP 8.3 12,761,472 -> 1,224,552 B.
|
||||
- 800k metadata scalars, 1,600,070 bytes: PHP 7.4 35,656,088 -> 2,051,392 B; PHP 8.3 18,879,104 -> 2,043,752 B.
|
||||
- Rejection before json_decode at offsets 300,105 and 800,049; approximately 89–94% peak reduction.
|
||||
- Existing PHP regression suite passes all 233 assertions baseline and gated on BOTH versions. Thirteen extra scanner assertions also pass.
|
||||
- Normal v1, large escaped strings, and 100,000 simple frames remain accepted. The last still uses ~43.4 MB on PHP 7.4 / ~25.3 MB on 8.3.
|
||||
- Scanning increases CPU time, up to ~455 ms in one WASM sample.
|
||||
|
||||
## Decisions and unverified work before formal fix
|
||||
|
||||
Candidates are experiments, not approved defaults: 32 MiB overall, 2 MiB v1, 256 KiB JSONL line, 100,000 events, 1,000 markers, depth 16, dimensions <=1,000 per axis. PHP gate separately experiments with 100,016 containers / 400,000 scalar-and-key tokens.
|
||||
|
||||
Upstream accepts zero dimensions as defaults and skips blank/non-event lines; the prototype follows stricter existing upload behavior. Applying this remotely changes compatibility and must be deliberately resolved. Per-axis bounds still admit one million terminal cells; a total-cell/work budget requires profiling. Current JS v1 prototype stores line strings until bounded whole-document preflight; production implementation should avoid large per-line overhead. A single oversized stream chunk may already be allocated by the platform before code can reject it. Default deadlines, cancellation on source changes/disposal, credential/CORS behavior, localization, multiple-player aggregate memory and real WordPress/browser playback need integration validation. Native PHP deployment memory is not established by WASM results.
|
||||
|
||||
Recommendation: the mitigation mechanism is empirically effective for the tested PHP and parser-input paths. Do not call all three findings fixed or choose final thresholds yet. Resolve compatibility and obtain browser/native integration evidence before publishing a formal patch.
|
||||
|
||||
## Scope
|
||||
|
||||
These are prior local measurements. CI artifacts provide separate native PHP and browser results. Experimental files are not loaded by the plugin.
|
||||
@@ -1,20 +0,0 @@
|
||||
# Isolated recording budget experiment
|
||||
|
||||
This branch adds experiments only. The plugin never loads these files. No formal fix, release, deployment or security finding closure is implied.
|
||||
|
||||
`resource-budget-experiment.yml` runs native PHP 7.4/8.3 and real Chromium with the pinned player 3.17.0. Results are retained as seven-day Actions artifacts. Browser payload delivery permits only controlled loopback fixtures; PHP runtime has networking disabled. Setup downloads official runtimes and locked dependencies.
|
||||
|
||||
Run from checkout root:
|
||||
|
||||
- `npm ci --ignore-scripts`
|
||||
- `npx --no-install playwright install --with-deps chromium`
|
||||
- `node experiment/browser.cjs`
|
||||
- `php -d memory_limit=128M experiment/php/run.php "$PWD" /tmp/cast-results`
|
||||
|
||||
The browser harness records actual DOM marker counts, playback/seek, same-origin iframe compatibility, diagnostic timings and sampled JS heap values. Heap samples are not total process RSS; timings are one run per case, not statistical performance claims. Large terminal dimensions run only through the rejection path. Marker cap 1,000 and total-cell adapter cap 40,000 are experimental candidates. The separate loader also has an optional cell budget; this harness explicitly identifies its adapter seam.
|
||||
|
||||
Compatibility differences are measured explicitly: current player accepts zero dimensions as defaults and ignores blank JSONL lines; the experimental loader follows stricter upload rules. These differences need a decision before any formal implementation. Compact single-line v1 remains rejected by this prototype, as in the existing upload path. The loader's read deadline does not interrupt synchronous parsing or guarantee an overall CPU limit; process/job watchdogs bound this experiment.
|
||||
|
||||
Native PHP fixtures are generated in temporary storage and capped below 2 MiB. Each measurement uses a fresh process with a 128 MiB PHP memory limit and 20-second watchdog. The original regression suite runs from a temporary copy with and without the gate. PHP tracked peak allocation is reported separately from OS memory. Permitting 100,000 normal frames still consumes meaningful memory.
|
||||
|
||||
Do not treat passing measurements as production readiness: actual WordPress integration, cross-origin/CORS behavior, multiple-player aggregate budgets, low-memory/mobile profiling and final compatibility/default choices remain separate work.
|
||||
@@ -1,50 +0,0 @@
|
||||
// Isolated experimental prototype; not production code.
|
||||
export const defaults = { bytes: 32*1024*1024, line: 256*1024, v1Bytes: 2*1024*1024, events:100000, markers:1000, depth:16, tokens:500000, lineTokens:20000, dimension:1000 };
|
||||
export function complexity(text, {depth,tokens}) {
|
||||
let quoted=false, escaped=false, nesting=0, count=0, primitive=false;
|
||||
for(let i=0;i<text.length;i++) {
|
||||
const c=text[i];
|
||||
if(quoted) { if(escaped) escaped=false; else if(c==='\\') escaped=true; else if(c==='"') quoted=false; continue; }
|
||||
if(c==='"') { quoted=true; primitive=false; if(++count>tokens) throw Error('complexity'); }
|
||||
else if(c==='['||c==='{') { primitive=false; if(++nesting>depth) throw Error('depth'); if(++count>tokens) throw Error('complexity'); }
|
||||
else if(c===']'||c==='}') { primitive=false; if(--nesting<0) throw Error('invalid'); }
|
||||
else if(c===','||c===':'||/\s/.test(c)) primitive=false;
|
||||
else if(!primitive) { primitive=true; if(++count>tokens) throw Error('complexity'); }
|
||||
}
|
||||
if(quoted||nesting!==0) throw Error('invalid');
|
||||
return count;
|
||||
}
|
||||
export async function loadBounded(response, limits={}, metrics={}) {
|
||||
const l={...defaults,...limits}; Object.assign(metrics,{bytes:0,lines:0,events:0,markers:0,parsed:0,canceled:false});
|
||||
if(!response.ok||!response.body?.getReader) throw Error('response');
|
||||
const reader=response.body.getReader(); const decoder=new TextDecoder('utf-8',{fatal:true});
|
||||
const deadline=performance.now()+(l.totalTimeoutMs??30000);
|
||||
async function read(){let timer;try{return await Promise.race([reader.read(),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('timeout')),Math.max(0,Math.min(l.readTimeoutMs??5000,deadline-performance.now())));})]);}finally{clearTimeout(timer);}}
|
||||
let pending='', lineBytes=0, first=true, mode, header, events=[], v1=[],time=0;
|
||||
const finite=x=>typeof x==='number'&&Number.isFinite(x)&&x>=0&&Number.isFinite(x*1000);
|
||||
const dim=x=>Number.isInteger(x)&&x>0&&x<=l.dimension;
|
||||
const parse=s=>{complexity(s,{depth:l.depth,tokens:l.lineTokens});metrics.parsed++; return JSON.parse(s);};
|
||||
function checkHeader(h){ if(!h||![1,2,3].includes(h.version))throw Error('header'); const t=h.version===3?h.term:h;if(!t||!dim(h.version===3?t.cols:t.width)||!dim(h.version===3?t.rows:t.height))throw Error('dimensions'); if(l.cells && (h.version===3?t.cols:t.width)*(h.version===3?t.rows:t.height)>l.cells)throw Error('cells'); for(const k of ['duration','idle_time_limit'])if(k in h&&!finite(h[k]))throw Error('time'); }
|
||||
function line(s){
|
||||
metrics.lines++;
|
||||
if(first){first=false;try{header=parse(s);}catch{mode='v1';v1.push(s+'\n');return;}checkHeader(header);if(header.version===1)throw Error('compact-v1');mode='jsonl';return;}
|
||||
if(mode==='v1'){v1.push(s+'\n');return;}
|
||||
if(++metrics.events>l.events)throw Error('events');
|
||||
if(header.version===3&&s[0]==='#')return;
|
||||
if(s[0]!=='[')throw Error('event'); const e=parse(s);
|
||||
if(!Array.isArray(e)||e.length!==3||!finite(e[0])||typeof e[1]!=='string'||!e[1]||typeof e[2]!=='string')throw Error('event');
|
||||
if(header.version===2&&e[0]<time)throw Error('time');time=header.version===2?e[0]:time+e[0];if(!finite(time))throw Error('time');
|
||||
if(e[1]==='r'){const m=/^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/.exec(e[2]);if(!m||!dim(+m[1])||!dim(+m[2]))throw Error('dimensions');if(l.cells&&(+m[1])*(+m[2])>l.cells)throw Error('cells');}
|
||||
if(e[1]==='m'&&++metrics.markers>l.markers)throw Error('markers'); events.push(e);
|
||||
}
|
||||
try {
|
||||
while(true){const {value,done}=await read();if(done)break;
|
||||
metrics.bytes+=value.byteLength;if(metrics.bytes>l.bytes||(mode==='v1'&&metrics.bytes>l.v1Bytes))throw Error('bytes');
|
||||
let start=0;
|
||||
for(let i=0;i<=value.length;i++)if(i===value.length||value[i]===10){const part=value.subarray(start,i);lineBytes+=part.length;if(mode!=='v1'&&lineBytes>l.line)throw Error('line');pending+=decoder.decode(part,{stream:true});if(i<value.length){line(pending);pending='';lineBytes=0;start=i+1;}}
|
||||
}
|
||||
pending+=decoder.decode();if(pending)line(pending);
|
||||
if(mode==='v1'){if(metrics.bytes>l.v1Bytes)throw Error('bytes');const text=v1.join('');complexity(text,{depth:l.depth,tokens:l.tokens});metrics.parsed++;const h=JSON.parse(text);checkHeader(h);if(h.version!==1||!Array.isArray(h.stdout)||h.stdout.length>l.events)throw Error('v1');for(const e of h.stdout){if(!Array.isArray(e)||e.length!==2||!finite(e[0])||typeof e[1]!=='string')throw Error('v1');time+=e[0];if(!finite(time))throw Error('time');}metrics.events=h.stdout.length;return h;}
|
||||
if(!header||!events.length)throw Error('empty');return [header,...events];
|
||||
}catch(e){metrics.canceled=true;await reader.cancel(e.message).catch(()=>{});throw e;}finally{reader.releaseLock();}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
'use strict';
|
||||
// Isolated CI experiment. No app source changes. Run from repository root.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
const crypto = require('node:crypto');
|
||||
const assert = require('node:assert/strict');
|
||||
const { chromium } = require('playwright');
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const OUT = path.join(ROOT, 'experiment', 'results', 'browser', 'results.json');
|
||||
const PLAYER = path.join(ROOT, 'node_modules', 'asciinema-player');
|
||||
const CAP = 1000, CELL_CAP = 40000; // Experimental policy candidates, not production recommendations.
|
||||
const results = [];
|
||||
const report = { metadata: { node: process.version, markerCap: CAP, cellCap: CELL_CAP, maxTestMarkers: 3000, repetitions: 1, caveat: 'Controlled CI measurements do not establish safe production or mobile thresholds. This run exercises total-cell checks through an adapter seam rather than the optional loader cell budget.' }, results };
|
||||
fs.mkdirSync(path.dirname(OUT), { recursive: true });
|
||||
const save = () => fs.writeFileSync(OUT, JSON.stringify(report, null, 2));
|
||||
const hardStop = setTimeout(() => { report.fatal = 'Overall 240-second experiment deadline'; save(); process.exit(1); }, 240000);
|
||||
const fixtures = new Map();
|
||||
function markers(n) {
|
||||
const events = [[0,'o','START\r\n'],[2.5,'o','END\r\n'],[3,'o','DONE\r\n']];
|
||||
for (let i=0;i<n;i++) events.push([0.1+i*2.3/Math.max(n,1),'m',`mark-${i}`]);
|
||||
events.sort((a,b)=>a[0]-b[0]);
|
||||
return [JSON.stringify({version:2,width:40,height:6}),...events.map(JSON.stringify)].join('\n')+'\n';
|
||||
}
|
||||
for (const n of [0,100,500,1000,1001,3000]) fixtures.set(`markers-${n}`,markers(n));
|
||||
for (const name of ['hello.cast','v1-pretty.cast','v3-comments.cast']) fixtures.set(name,fs.readFileSync(path.join(ROOT,'tests','fixtures',name),'utf8'));
|
||||
fixtures.set('late-resize','{"version":2,"width":40,"height":6}\n[0,"o","START"]\n[1,"r","1001x24"]\n[3,"o","END"]\n');
|
||||
fixtures.set('large-initial-cells','{"version":2,"width":1000,"height":1000}\n[0,"o","START"]\n[3,"o","END"]\n');
|
||||
fixtures.set('large-resize-cells','{"version":2,"width":40,"height":6}\n[0,"o","START"]\n[1,"r","1000x1000"]\n[3,"o","END"]\n');
|
||||
fixtures.set('compat-zero-dimensions','{"version":2,"width":0,"height":0}\n[0,"o","COMPAT\\r\\n"]\n[3,"o","done"]\n');
|
||||
fixtures.set('compat-blank-lines','{"version":2,"width":40,"height":6}\n\n[0,"o","COMPAT\\r\\n"]\n[3,"o","done"]\n');
|
||||
const html='<!doctype html><html><head><link rel="icon" href="data:,"><link rel="stylesheet" href="/player.css"></head><body><div id="player"></div><script src="/player.js"></script></body></html>';
|
||||
const assets = new Map([
|
||||
['/player.js',[path.join(PLAYER,'dist/bundle/asciinema-player.min.js'),'text/javascript']],
|
||||
['/player.css',[path.join(PLAYER,'dist/bundle/asciinema-player.css'),'text/css']],
|
||||
['/loader.mjs',[path.join(ROOT,'experiment/bounded-loader.mjs'),'text/javascript']]
|
||||
]);
|
||||
let server;
|
||||
async function runCase(origin, c) {
|
||||
let browser;
|
||||
const errors=[];
|
||||
const timer=setTimeout(()=>{results.push({...c,error:'Hard 25-second case deadline'});save();process.exit(1);},25000);
|
||||
try {
|
||||
browser=await chromium.launch({headless:true,timeout:10000,...(process.env.CHROMIUM_EXECUTABLE ? {executablePath:process.env.CHROMIUM_EXECUTABLE}: {}),args:['--js-flags=--max-old-space-size=256','--enable-precise-memory-info']});
|
||||
report.metadata.chromium=browser.version();
|
||||
const context=await browser.newContext({serviceWorkers:'block',viewport:{width:1280,height:900}});
|
||||
await context.route('**/*', async route=>{
|
||||
const u=new URL(route.request().url());
|
||||
const allowed=u.origin===origin && (u.pathname==='/' || u.pathname==='/frame' || assets.has(u.pathname) || (u.pathname.startsWith('/fixture/') && fixtures.has(decodeURIComponent(u.pathname.slice(9)))));
|
||||
if(allowed) await route.continue(); else { errors.push(`Blocked unexpected request: ${u.origin}${u.pathname}`); await route.abort(); }
|
||||
});
|
||||
const page=await context.newPage();page.setDefaultTimeout(10000);
|
||||
page.on('pageerror', e=>errors.push(String(e)));
|
||||
await page.goto(origin+'/',{waitUntil:'load'});
|
||||
let frame=page.mainFrame();
|
||||
if(c.realm==='iframe') {
|
||||
await page.evaluate(()=>{const f=document.createElement('iframe');f.id='test-frame';f.src='/frame';document.body.appendChild(f);});
|
||||
const handle=await page.waitForSelector('#test-frame');frame=await handle.contentFrame();
|
||||
await frame.waitForFunction(()=>typeof AsciinemaPlayer!=='undefined');
|
||||
}
|
||||
const r=await frame.evaluate(async c=>{
|
||||
const {loadBounded}=await import('/loader.mjs');
|
||||
const heapBefore=performance.memory?.usedJSHeapSize??null;const metrics={};const before=document.querySelectorAll('*').length;
|
||||
let playerCalls=0, p, data;const started=performance.now();
|
||||
// Adapter seam deliberately runs after bounded parsing and before real player creation.
|
||||
function checkCells(parsed) {
|
||||
const h=Array.isArray(parsed)?parsed[0]:parsed;
|
||||
const w=h.version===3?h.term.cols:h.width, rows=h.version===3?h.term.rows:h.height;
|
||||
if(w*rows>c.cellCap) throw Error('cells');
|
||||
if(Array.isArray(parsed)) for(const e of parsed.slice(1)) if(e[1]==='r') {
|
||||
const [cols,rows]=e[2].split('x').map(Number);if(cols*rows>c.cellCap)throw Error('cells');
|
||||
}
|
||||
}
|
||||
try {
|
||||
const response=await fetch('/fixture/'+encodeURIComponent(c.fixture));
|
||||
if(c.mode==='prototype') {data=await loadBounded(response,{markers:c.cap},metrics);checkCells(data);}
|
||||
else data=await response.text();
|
||||
} catch(e) {
|
||||
return {rejected:true,error:e.message,playerCalls,metrics,elapsedMs:performance.now()-started,domAdded:document.querySelectorAll('*').length-before,markerElements:document.querySelectorAll('.ap-marker-container').length};
|
||||
}
|
||||
const loadedMs=performance.now()-started;
|
||||
playerCalls++;p=AsciinemaPlayer.create({data},document.getElementById('player'),{preload:true,controls:true});
|
||||
try {
|
||||
await p.play();await p.pause();await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));
|
||||
void document.body.offsetHeight;
|
||||
const readyMs=performance.now()-started;
|
||||
const domElements=document.querySelectorAll('*').length;
|
||||
const markerElements=document.querySelectorAll('.ap-marker-container').length;
|
||||
const duration=await p.getDuration();
|
||||
await p.seek(0);await p.play();
|
||||
const playbackStart=performance.now();let advanced=0;
|
||||
while(performance.now()-playbackStart<2500) {advanced=await p.getCurrentTime();if(advanced>0.02)break;await new Promise(r=>setTimeout(r,50));}
|
||||
await p.pause();const seekTo=c.markerCount===undefined?Math.max(0.2,duration*0.8):2.8;
|
||||
const seekStart=performance.now();await p.seek(seekTo);await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));
|
||||
const seekMs=performance.now()-seekStart,seekTime=await p.getCurrentTime();
|
||||
const terminal=document.querySelector('.ap-term-text')?.textContent||'';
|
||||
const heapAfter=performance.memory?.usedJSHeapSize??null;return {heapBefore,heapAfter,heapDelta:heapAfter===null?null:heapAfter-heapBefore,rejected:false,playerCalls,metrics,loadedMs,readyMs,domElements,domAdded:domElements-before,markerElements,duration,advanced,seekTo,seekTime,seekMs,terminal,playbackOk:advanced>0.02,seekOk:Math.abs(seekTime-seekTo)<0.05&&terminal.includes(c.expectedText)&&(c.markerCount===undefined||!terminal.includes('DONE'))};
|
||||
} finally {p.dispose();}
|
||||
},{...c,cap:CAP,cellCap:CELL_CAP});
|
||||
const row={...c,...r,pageErrors:errors};results.push(row);save();
|
||||
assert.deepEqual(errors,[],`${c.fixture}: browser errors or unexpected requests`);
|
||||
if(c.reject) {assert.equal(r.rejected,true);assert.equal(r.error,c.reject);assert.equal(r.playerCalls,0);assert.equal(r.domAdded,0);assert.equal(r.markerElements,0);}
|
||||
else {assert.equal(r.rejected,false);assert.equal(r.playerCalls,1);assert.equal(r.playbackOk,true);assert.equal(r.seekOk,true);assert.equal(r.markerElements,c.markerCount??0);assert.ok(r.duration>0);}
|
||||
row.passed=true;save();console.log(JSON.stringify({fixture:c.fixture,mode:c.mode,realm:c.realm,passed:true,rejected:r.rejected,markers:r.markerElements,readyMs:r.readyMs,seekMs:r.seekMs}));
|
||||
} catch(e) {results.push({...c,failed:true,error:String(e)});save();throw e;}
|
||||
finally {if(browser)await browser.close();clearTimeout(timer);}
|
||||
}
|
||||
(async()=>{
|
||||
report.metadata.player=JSON.parse(fs.readFileSync(path.join(PLAYER,'package.json'),'utf8')).version;
|
||||
assert.equal(report.metadata.player,'3.17.0');
|
||||
report.metadata.playwright=require('playwright/package.json').version;
|
||||
report.metadata.bundleSha256=crypto.createHash('sha256').update(fs.readFileSync(assets.get('/player.js')[0])).digest('hex');save();
|
||||
server=http.createServer((req,res)=>{
|
||||
const u=new URL(req.url,'http://127.0.0.1');
|
||||
if(req.method!=='GET'){res.writeHead(405).end();return;}
|
||||
if(u.pathname==='/'||u.pathname==='/frame'){res.writeHead(200,{'Content-Type':'text/html'}).end(html);return;}
|
||||
if(assets.has(u.pathname)){const [file,type]=assets.get(u.pathname);res.writeHead(200,{'Content-Type':type}).end(fs.readFileSync(file));return;}
|
||||
if(u.pathname.startsWith('/fixture/')){const text=fixtures.get(decodeURIComponent(u.pathname.slice(9)));if(text!==undefined){res.writeHead(200,{'Content-Type':'application/x-asciicast'}).end(text);return;}}
|
||||
res.writeHead(404).end();
|
||||
});
|
||||
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));const origin=`http://127.0.0.1:${server.address().port}`;
|
||||
for(const count of [0,100,500,1000,1001,3000]) for(const mode of ['baseline','prototype'])
|
||||
await runCase(origin,{fixture:`markers-${count}`,markerCount:count,mode,realm:'top',expectedText:'END',...(mode==='prototype'&&count>CAP?{reject:'markers'}:{})});
|
||||
for(const [fixture,expectedText] of [['hello.cast','Hello from wp-asciiplayer'],['v1-pretty.cast','Pretty v1 recording'],['v3-comments.cast','Commented v3 recording']])
|
||||
for(const realm of ['top','iframe']) for(const mode of ['baseline','prototype'])await runCase(origin,{fixture,expectedText,mode,realm});
|
||||
// Observe rather than hide upstream-tolerated compatibility differences.
|
||||
for(const [fixture,reject] of [['compat-zero-dimensions','dimensions'],['compat-blank-lines','event']])for(const mode of ['baseline','prototype'])await runCase(origin,{fixture,expectedText:'COMPAT',mode,realm:'top',...(mode==='prototype'?{reject}:{})});
|
||||
// No baseline for dangerous dimensions: zero real player calls required.
|
||||
for(const [fixture,reject] of [['late-resize','dimensions'],['large-initial-cells','cells'],['large-resize-cells','cells']])await runCase(origin,{fixture,reject,mode:'prototype',realm:'top'});
|
||||
report.completed=true;save();console.log(`PASS: ${results.filter(r=>r.passed).length} controlled browser cases. Marker cap ${CAP} is experimental.`);
|
||||
})().catch(e=>{report.fatal=String(e);save();console.error(e);process.exitCode=1;}).finally(()=>{if(server)server.close();clearTimeout(hardStop);});
|
||||
@@ -1,17 +0,0 @@
|
||||
# Native PHP allocation experiment (not production code)
|
||||
|
||||
Run from an unchanged plugin checkout, with this directory copied to `experiment/php`:
|
||||
|
||||
php -d memory_limit=128M experiment/php/run.php /repo /results
|
||||
|
||||
Requires native PHP 7.4+ CLI with `proc_open`; no Python, Composer, network, or downloaded dependency is needed. Run separately under PHP 7.4 and 8.3. `/repo` is the checkout root, `/results` a writable artifact directory. A readonly checkout is supported. The controller creates only temporary data under the system temporary directory and raw outputs plus `results.json` under the specified results directory.
|
||||
|
||||
Suggested isolation: official `php:7.4-cli` / `php:8.3-cli` Docker images, network disabled, 512 MiB container memory, read-only root, writable 256 MiB `/tmp` tmpfs, checkout mounted `/repo:ro`, result directory mounted `/results:rw`.
|
||||
|
||||
Each measurement launches a fresh native PHP subprocess with `memory_limit=128M` and a 20-second controller watchdog. Synthetic fixtures stay below the existing 2 MiB v1 cap. No large fixtures are checked in. The controller compares baseline and gated validation, asserts expected acceptance/rejection and rejection positions, and requires >50% lower PHP tracked peak on both deliberately wide rejected shapes. It records exact PHP version, integer size, bytes, tracked/allocated peaks, timings, and whether decode was reached. Runtime failure, unexpected validity, insufficient reduction, or regression-test failure makes the controller exit nonzero.
|
||||
|
||||
The original suite (229 assertions without build/runtime.asset.php, 233 with it) runs on a temporary copy, first unchanged and then with the experimental gate injected at the start of `is_cast_v1`. All production sources remain unchanged. Thirteen focused scanner assertions also run.
|
||||
|
||||
The gate is a lexical budget check, not a JSON validator. It respects strings/backslash escapes without constructing a token array. Limits are experimental (100,016 containers, 400,000 scalar/key tokens, depth 15), intentionally admitting 100,000 minimal frames. Existing byte limits and downstream JSON/schema validation remain necessary. Large previously valid metadata can now be rejected, and legal 100,000-frame recordings still allocate substantial memory. CI results do not establish production WordPress memory headroom or concurrent-request safety. Timing is recorded but no speedup is promised.
|
||||
|
||||
All child stdout/stderr is saved, including on failure. The machine-readable summary is `/results/results.json`. Local syntax/measurement checks use WASM only; success of native CLI orchestration must be established by CI.
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
// One fresh CLI process per measurement; fixtures generated by the controller.
|
||||
$root=$argv[1]; $input=$argv[2]; $mode=$argv[3];
|
||||
define('ABSPATH', '/');
|
||||
require $root.'/includes/uploads.php';
|
||||
require __DIR__.'/preflight.php';
|
||||
$text=file_get_contents($input);
|
||||
if ($text === false || strlen($text)>2097152) throw new RuntimeException('Unexpected fixture size.');
|
||||
$before=memory_get_usage(false); $before_real=memory_get_usage(true);
|
||||
$start=microtime(true); $decoded=false; $gate=null;
|
||||
if ($mode==='gated') $gate=preflight_budget($text);
|
||||
if ($gate===null || $gate['ok']) {$valid=\LamGC\Asciiplayer\is_cast_v1($text);$decoded=true;}
|
||||
else $valid=false;
|
||||
echo json_encode(array('php'=>PHP_VERSION,'sapi'=>PHP_SAPI,'int_size'=>PHP_INT_SIZE,'mode'=>$mode,'input_bytes'=>strlen($text),'memory_limit'=>ini_get('memory_limit'),'before_bytes'=>$before,'before_real_bytes'=>$before_real,'peak_bytes'=>memory_get_peak_usage(false),'peak_real_bytes'=>memory_get_peak_usage(true),'elapsed_ms'=>round((microtime(true)-$start)*1000,3),'decoded'=>$decoded,'valid'=>$valid,'gate'=>$gate),JSON_THROW_ON_ERROR)."\n";
|
||||
@@ -1,28 +0,0 @@
|
||||
<?php
|
||||
// Experiment only: a lexical resource gate, NOT a replacement JSON validator.
|
||||
// Constant scanner state; no token list and no decoded object graph.
|
||||
function preflight_budget($text, $container_limit = 100016, $token_limit = 400000) {
|
||||
$n = strlen($text); $containers = 0; $tokens = 0; $depth = 0;
|
||||
$in_string = false; $escaped = false; $in_atom = false;
|
||||
for ($i = 0; $i < $n; ++$i) {
|
||||
$c = $text[$i];
|
||||
if ($in_string) {
|
||||
if ($escaped) { $escaped = false; }
|
||||
elseif ($c === '\\') { $escaped = true; }
|
||||
elseif ($c === '"') { $in_string = false; }
|
||||
continue;
|
||||
}
|
||||
if ($c === '"') { $in_string = true; $in_atom = false; ++$tokens; }
|
||||
elseif ($c === '{' || $c === '[') {
|
||||
$in_atom = false; ++$containers; ++$depth;
|
||||
if ($depth > 15) return array('ok'=>false,'reason'=>'depth','offset'=>$i,'containers'=>$containers,'tokens'=>$tokens);
|
||||
}
|
||||
elseif ($c === '}' || $c === ']') { --$depth; $in_atom = false; }
|
||||
elseif ($c === ',' || $c === ':' || $c === ' ' || $c === "\n" || $c === "\r" || $c === "\t") { $in_atom = false; }
|
||||
elseif (!$in_atom) { ++$tokens; $in_atom = true; }
|
||||
if ($containers > $container_limit || $tokens > $token_limit) {
|
||||
return array('ok'=>false,'reason'=>$containers > $container_limit ? 'containers' : 'tokens','offset'=>$i,'containers'=>$containers,'tokens'=>$tokens);
|
||||
}
|
||||
}
|
||||
return array('ok'=>true,'reason'=>'within_budget','offset'=>$n,'containers'=>$containers,'tokens'=>$tokens);
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
<?php
|
||||
/** Native PHP 7.4+ CLI only. Usage: php -d memory_limit=128M run.php REPO_ROOT RESULTS_DIR */
|
||||
if (PHP_SAPI!=='cli') throw new RuntimeException('CLI required.');
|
||||
$root=realpath($argv[1] ?? dirname(__DIR__,2));
|
||||
$out=$argv[2] ?? sys_get_temp_dir().'/cast-budget-results';
|
||||
if (!$root || !is_file($root.'/includes/uploads.php')) throw new RuntimeException('Supply plugin checkout root.');
|
||||
if (!is_dir($out) && !mkdir($out,0700,true)) throw new RuntimeException('Cannot create output directory.');
|
||||
$out=realpath($out);$temp=sys_get_temp_dir().'/cast-budget-'.bin2hex(random_bytes(8));mkdir($temp,0700);
|
||||
$report=array('php'=>PHP_VERSION,'sapi'=>PHP_SAPI,'memory_limit'=>'128M','timeout_seconds'=>20,'budget'=>array('containers'=>100016,'tokens'=>400000,'depth'=>15),'measurements'=>array(),'checks'=>array(),'errors'=>array());
|
||||
function run_child($args,$label) {
|
||||
global $out;
|
||||
$stdout=$out.'/'.$label.'.stdout';$stderr=$out.'/'.$label.'.stderr';
|
||||
$command=array_merge(array(PHP_BINARY,'-d','memory_limit=128M','-d','display_errors=stderr','-d','log_errors=0'),$args);
|
||||
$process=proc_open($command,array(0=>array('file','/dev/null','r'),1=>array('file',$stdout,'w'),2=>array('file',$stderr,'w')),$pipes);
|
||||
if (!is_resource($process)) throw new RuntimeException('Cannot start '.$label);
|
||||
$deadline=microtime(true)+20;$timed_out=false;
|
||||
do {$status=proc_get_status($process);if(!$status['running'])break;if(microtime(true)>$deadline){$timed_out=true;proc_terminate($process,9);break;}usleep(10000);}while(true);
|
||||
$closed=proc_close($process);$exit=$status['exitcode']>=0?$status['exitcode']:$closed;
|
||||
$record=array('label'=>$label,'exit_code'=>$exit,'timed_out'=>$timed_out,'stdout_file'=>basename($stdout),'stderr_file'=>basename($stderr));
|
||||
if($timed_out || $exit!==0)throw new RuntimeException($label.' failed: '.json_encode($record).' '.file_get_contents($stderr));
|
||||
return array($record,file_get_contents($stdout));
|
||||
}
|
||||
function check($condition,$label){global $report;$report['checks'][]=array('label'=>$label,'passed'=>(bool)$condition);if(!$condition)$report['errors'][]=$label;}
|
||||
function copy_tree($src,$dst){if(is_dir($src)){if(!is_dir($dst))mkdir($dst,0700,true);foreach(scandir($src) as $name)if($name!=='.'&&$name!=='..')copy_tree($src.'/'.$name,$dst.'/'.$name);}else{if(!is_dir(dirname($dst)))mkdir(dirname($dst),0700,true);if(!copy($src,$dst))throw new RuntimeException('Copy failed: '.$src);}}
|
||||
function clean_tree($dir){foreach(scandir($dir) as $name){if($name==='.'||$name==='..')continue;$p=$dir.'/'.$name;if(is_dir($p))clean_tree($p);else unlink($p);}rmdir($dir);}
|
||||
try {
|
||||
$base="{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[[0,\"ok\"]],\"metadata\":";
|
||||
$fixtures=array(
|
||||
'normal-fixture'=>file_get_contents($root.'/tests/fixtures/v1-pretty.cast'),
|
||||
'normal-100k-frames'=>"{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":[".str_repeat('[0,""],',99999).'[0,""]]}',
|
||||
'escaped-strings'=>json_encode(array('version'=>1,'width'=>80,'height'=>24,'stdout'=>array(array(0,'\\"[{]}\\\\" ,: true false null')),'metadata'=>str_repeat('[{},',120000))),
|
||||
'wide-empty-objects'=>$base.'['.str_repeat('{},',259999).'{}]}',
|
||||
'wide-scalars'=>$base.'['.str_repeat('0,',799999).'0]}'
|
||||
);
|
||||
$properties=array();for($i=0;$i<120000;++$i)$properties[]='"k'.$i.'":0';$fixtures['wide-properties']=$base.'{'.implode(',',$properties).'}}';unset($properties);
|
||||
foreach($fixtures as $name=>$contents){if(strlen($contents)>2097152)throw new RuntimeException('Fixture exceeds 2 MiB');file_put_contents($temp.'/'.$name.'.cast',$contents);}
|
||||
unset($fixtures,$contents);
|
||||
foreach(array('normal-fixture','normal-100k-frames','escaped-strings','wide-empty-objects','wide-scalars','wide-properties') as $name){
|
||||
$pair=array();foreach(array('baseline','gated') as $mode){list($process,$text)=run_child(array(__DIR__.'/measure.php',$root,$temp.'/'.$name.'.cast',$mode),$name.'-'.$mode);$result=json_decode($text,true,512,JSON_THROW_ON_ERROR);$pair[$mode]=$result;check($result['sapi']==='cli' && $result['memory_limit']==='128M',$name.' '.$mode.' native CLI and memory limit');$report['measurements'][]=array('fixture'=>$name,'process'=>$process,'result'=>$result);}
|
||||
check($pair['baseline']['valid']===true,$name.' baseline accepted');
|
||||
$reject=in_array($name,array('wide-empty-objects','wide-scalars'),true);
|
||||
check($pair['gated']['valid']===!$reject,$name.' expected gated validity');
|
||||
check($pair['gated']['decoded']===!$reject,$name.' expected decode reached/skipped');
|
||||
if($reject){check($pair['gated']['peak_bytes']<$pair['baseline']['peak_bytes']*0.5,$name.' tracked peak reduced by >50%');$expected=$name==='wide-empty-objects'?300105:800049;check($pair['gated']['gate']['offset']===$expected,$name.' expected rejection offset');}
|
||||
}
|
||||
list($process,$text)=run_child(array(__DIR__.'/scanner-tests.php'),'scanner-tests');check(strpos($text,'13 scanner assertions passed.')!==false,'13 scanner assertions');$report['scanner_process']=$process;
|
||||
$copy=$temp.'/plugin';mkdir($copy);foreach(array('asciicast-player.php','includes','tests/php','tests/fixtures') as $item)copy_tree($root.'/'.$item,$copy.'/'.$item);
|
||||
foreach(array('index.asset.php','view.asset.php','runtime.asset.php') as $item)if(is_file($root.'/build/'.$item))copy_tree($root.'/build/'.$item,$copy.'/build/'.$item);
|
||||
$expected_assertions=is_file($root.'/build/runtime.asset.php')?233:229;
|
||||
$report['expected_suite_assertions']=$expected_assertions;
|
||||
foreach(array('baseline','gated') as $mode){
|
||||
if($mode==='gated'){$source=file_get_contents($copy.'/includes/uploads.php');$needle='function is_cast_v1( $text ) {';if(substr_count($source,$needle)!==1)throw new RuntimeException('Injection marker missing/ambiguous.');$source=str_replace($needle,$needle."\n if (!\\preflight_budget(\$text)['ok']) return false;",$source);file_put_contents($copy.'/includes/uploads.php',$source);}
|
||||
$wrapper=$temp.'/suite-'.$mode.'.php';file_put_contents($wrapper,"<?php require ".var_export(__DIR__.'/preflight.php',true).'; require '.var_export($copy.'/tests/php/run.php',true).';');
|
||||
list($process,$text)=run_child(array($wrapper),'suite-'.$mode);preg_match('/OK: ([0-9]+) assertions passed\./',$text,$match);$count=isset($match[1])?(int)$match[1]:0;check($count===$expected_assertions,'existing '.$expected_assertions.' assertions '.$mode);$report['suite_assertion_counts'][$mode]=$count;$report['suite_processes'][$mode]=$process;
|
||||
}
|
||||
check($report['suite_assertion_counts']['baseline']===$report['suite_assertion_counts']['gated'],'baseline and gated suite counts equal');
|
||||
} catch(Throwable $error){$report['errors'][]=$error->getMessage();}
|
||||
$report['passed']=count($report['errors'])===0;
|
||||
file_put_contents($out.'/results.json',json_encode($report,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR)."\n");
|
||||
echo json_encode(array('passed'=>$report['passed'],'php'=>PHP_VERSION,'measurements'=>count($report['measurements']),'checks'=>count($report['checks']),'errors'=>$report['errors'],'results'=>$out.'/results.json'),JSON_THROW_ON_ERROR)."\n";
|
||||
clean_tree($temp);exit($report['passed']?0:1);
|
||||
@@ -1,16 +0,0 @@
|
||||
<?php
|
||||
require __DIR__.'/preflight.php';
|
||||
$n=0;
|
||||
function check($ok,$msg){global $n;++$n;if(!$ok)throw new Exception($msg);}
|
||||
$cases=array(
|
||||
array('{}',1,0),array('[]',1,0),array('{"a":[]}',2,1),
|
||||
array('[0,true,false,null,-1.2e+3]',1,5),
|
||||
array(json_encode(array('title'=>'[[{{,:', 'escaped'=>'\\"[{]}\\\\"','arr'=>array(0,'"'))),2,7)
|
||||
);
|
||||
foreach($cases as $case){$r=preflight_budget($case[0]);check($r['ok']&&$r['containers']===$case[1]&&$r['tokens']===$case[2],'count '. $case[0]);}
|
||||
check(preflight_budget('[[],{}]',3,0)['ok'],'exact container boundary');
|
||||
check(!preflight_budget('[[],{}]',2,0)['ok'],'container +1 rejected');
|
||||
check(preflight_budget('[0,1,"x"]',1,3)['ok'],'exact token boundary');
|
||||
check(!preflight_budget('[0,1,"x"]',1,2)['ok'],'token +1 rejected');
|
||||
foreach(array('[','[1,]','{"x":}', '["unterminated') as $bad){$r=preflight_budget($bad);json_decode($bad,false,16);check(!$r['ok'] || json_last_error()!==JSON_ERROR_NONE,'invalid JSON rejected by final decoder');}
|
||||
echo "OK: $n scanner assertions passed.\n";
|
||||
Reference in New Issue
Block a user