diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml
index d521c32..718f8fe 100644
--- a/.github/workflows/php.yml
+++ b/.github/workflows/php.yml
@@ -26,7 +26,7 @@ jobs:
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
- extensions: curl, intl, mbstring, pdo_sqlite
+ extensions: curl, intl, mbstring, mongodb, pcntl, pdo_sqlite, posix, sockets
tools: composer:v2
github-token: ${{ secrets.GITHUB_TOKEN }}
coverage: none
@@ -48,3 +48,37 @@ jobs:
else
echo 'No test script is declared for this package.'
fi
+
+ mongo-integration:
+ name: MongoDB integration
+ runs-on: ubuntu-24.04
+ services:
+ mongodb:
+ image: mongo:7.0
+ ports:
+ - 27017:27017
+ options: >-
+ --health-cmd "mongosh --quiet --eval 'db.adminCommand({ ping: 1 }).ok'"
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v7
+
+ - name: Set up PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: '8.5'
+ extensions: mongodb
+ tools: composer:v2
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ coverage: none
+
+ - name: Install dependencies
+ run: composer install --prefer-dist --no-interaction --no-progress --no-scripts
+
+ - name: Run MongoDB integration test
+ run: composer test:mongo --no-interaction
+ env:
+ MONGODB_URI: mongodb://127.0.0.1:27017
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c71aa5b..3dd506a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,31 +1,18 @@
# Changelog
-All notable changes to this project will be documented in this file.
+Notable changes are recorded here. This project follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
-The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
-and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [2.0.0] - Unreleased
-## [1.0.0] - 2025-01-XX - LTS Release
+This dependency change requires the next major package release: Engine 9 uses the Server 7 session API, which is not available in the Engine 8.1 / Server 4 dependency graph.
### Added
-- Initial LTS release
-- Full documentation
-- Session management system
-- Multiple session drivers (file, redis, database)
-- Session encryption
-- Session expiration handling
-- Flash data support
-### Security
-- Secure session handling
-- Session data encryption
+- Compatibility with Triangle Engine 9 and Localzet Server 7.
+- Runtime compatibility tests for Engine bootstrap, Server session handlers, and file-backed session round trips.
+- A MongoDB integration test for session round trips and persistence behavior.
----
-
-## [Unreleased]
-
-### Planned
-- Additional session drivers
-- Session clustering support
-- Performance optimizations
+### Changed
+- MongoDB session writes disable PHP object instantiation and reject malformed or non-array payloads.
+- MongoDB session reads restore BSON documents and arrays as PHP arrays.
diff --git a/README.md b/README.md
index 4b71369..70e3484 100644
--- a/README.md
+++ b/README.md
@@ -19,3 +19,56 @@
+
+# Triangle Session
+
+Triangle Session connects Engine applications to the HTTP session storage provided by Localzet Server. It includes file, Redis, Redis Cluster and MongoDB handlers and a `session()` helper for the current request.
+
+## Requirements
+
+- PHP 8.1 or later
+- `triangle/engine` 9.x, which requires Localzet Server 7.1 or later
+
+## Installation
+
+```sh
+composer require triangle/session:^2.0
+```
+
+Engine 9 loads `Triangle\Session\Bootstrap` with its built-in components. This compatibility update is for the next major release because Engine 8.1 resolves to Server 4 and does not provide the Server 7 session API used by this package. To copy the package configuration into an application that does not publish package configuration automatically, run `Triangle\Session\Install::install()` in the application installation context. The default storage driver is `file`; its path comes from `runtime_path('sessions')`.
+
+## Using a session
+
+The helper operates on the current request's Server session:
+
+```php
+session(['user_id' => 42]);
+
+$userId = session('user_id');
+$theme = session('preferences.theme', 'light');
+```
+
+The helper returns the current session when called without a key, reads values for string keys, and writes the supplied values when given an array. Session storage is request-scoped by Server; use scalar values and arrays. Objects restored from stored payloads are not instantiated.
+
+## Storage drivers
+
+| Driver | Additional requirement | Configuration key |
+| --- | --- | --- |
+| `file` | Writable runtime directory | `session.config.file` |
+| `redis` | PHP Redis extension | `session.config.redis` |
+| `redis_cluster` | PHP Redis extension and a configured Redis Cluster | `session.config.redis_cluster` |
+| `mongo` | `mongodb/mongodb` and the PHP MongoDB extension | `session.config.mongo` |
+
+Set `SESSION_TYPE` to the selected driver and provide its connection details through the environment or `config/session.php`. For HTTPS deployments, set `SESSION_COOKIE_SECURE=true`; configure the cookie domain and SameSite policy for the application’s deployment topology.
+
+## Development checks
+
+```sh
+composer validate --strict --no-check-publish
+composer test
+composer audit --locked
+```
+
+The compatibility test exercises Engine bootstrap loading, Server session-handler contracts, file-backed round trips, and safe handling of serialized values. MongoDB and Redis network services are optional and are not started by this test.
+
+Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
diff --git a/README.ru.md b/README.ru.md
new file mode 100644
index 0000000..4c101d7
--- /dev/null
+++ b/README.ru.md
@@ -0,0 +1,52 @@
+# Triangle Session
+
+Triangle Session подключает HTTP-сессии Localzet Server к приложениям на Triangle Engine. В пакет входят обработчики для файлов, Redis, Redis Cluster и MongoDB, а также функция `session()` для доступа к сессии текущего запроса.
+
+## Требования
+
+- PHP 8.1 или новее
+- `triangle/engine` версии 9.x, которая требует Localzet Server 7.1 или новее
+
+## Установка
+
+```sh
+composer require triangle/session:^2.0
+```
+
+Engine 9 запускает `Triangle\Session\Bootstrap` вместе со встроенными компонентами. Это обновление совместимости предназначено для следующей основной версии: Engine 8.1 устанавливает Server 4, в котором нет используемого пакетом API сессий Server 7. Если приложение не публикует конфигурацию пакета автоматически, вызовите `Triangle\Session\Install::install()` в контексте установки приложения. По умолчанию используется файловое хранилище в каталоге `runtime_path('sessions')`.
+
+## Работа с сессией
+
+Функция работает с сессией текущего запроса:
+
+```php
+session(['user_id' => 42]);
+
+$userId = session('user_id');
+$theme = session('preferences.theme', 'light');
+```
+
+Вызов без ключа возвращает объект сессии, строковый ключ читает значение, массив записывает несколько значений. Хранилищем и временем жизни запроса управляет Server. Сохраняйте скаляры и массивы: объекты из сохранённого payload не создаются при чтении.
+
+## Хранилища
+
+| Драйвер | Дополнительное требование | Ключ конфигурации |
+| --- | --- | --- |
+| `file` | Доступный для записи каталог runtime | `session.config.file` |
+| `redis` | PHP-расширение Redis | `session.config.redis` |
+| `redis_cluster` | PHP-расширение Redis и настроенный Redis Cluster | `session.config.redis_cluster` |
+| `mongo` | `mongodb/mongodb` и PHP-расширение MongoDB | `session.config.mongo` |
+
+Укажите драйвер через `SESSION_TYPE`, а параметры подключения задайте в окружении или `config/session.php`. Для HTTPS включите `SESSION_COOKIE_SECURE=true`. Домен cookie и SameSite выберите с учётом схемы размещения приложения.
+
+## Проверки разработки
+
+```sh
+composer validate --strict --no-check-publish
+composer test
+composer audit --locked
+```
+
+Тест совместимости проверяет загрузку Engine bootstrap, контракты обработчиков Server, файловый цикл чтения и записи и безопасную обработку сериализованных значений. MongoDB и Redis не запускаются: сетевые сервисы для теста не требуются.
+
+Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
diff --git a/composer.json b/composer.json
index b1a7655..7dce7a6 100644
--- a/composer.json
+++ b/composer.json
@@ -31,14 +31,23 @@
},
"require": {
"php": "^8.1",
- "triangle/engine": "^8.1"
+ "triangle/engine": "^9.0"
+ },
+ "require-dev": {
+ "ext-mongodb": "*",
+ "mongodb/mongodb": "^2.0"
},
"suggest": {
+ "ext-redis": "For RedisSessionHandler and RedisClusterSessionHandler",
"mongodb/mongodb": "For MongoSessionHandler"
},
"config": {
"platform": {
"php": "8.1.0"
}
+ },
+ "scripts": {
+ "test": "php tests/session-compatibility.php",
+ "test:mongo": "php tests/mongo-integration.php"
}
}
diff --git a/src/Bootstrap.php b/src/Bootstrap.php
index d2b40fc..9156611 100644
--- a/src/Bootstrap.php
+++ b/src/Bootstrap.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
diff --git a/src/Config/session.php b/src/Config/session.php
index 6e85825..ee6e376 100644
--- a/src/Config/session.php
+++ b/src/Config/session.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
diff --git a/src/Handlers/FileSessionHandler.php b/src/Handlers/FileSessionHandler.php
index baaa121..f574722 100644
--- a/src/Handlers/FileSessionHandler.php
+++ b/src/Handlers/FileSessionHandler.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
diff --git a/src/Handlers/MongoSessionHandler.php b/src/Handlers/MongoSessionHandler.php
index 5a06ff0..8fac977 100644
--- a/src/Handlers/MongoSessionHandler.php
+++ b/src/Handlers/MongoSessionHandler.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
@@ -109,9 +109,14 @@ public function close(): bool
*/
public function read(string $sessionId): string
{
- $session = $this->collection->findOne(['_id' => $sessionId]);
+ $session = $this->collection->findOne(
+ ['_id' => $sessionId],
+ ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']],
+ );
if ($session !== null) {
- return serialize((array)$session);
+ $data = $session;
+ unset($data['_id'], $data['updated_at']);
+ return serialize($data);
}
return '';
}
@@ -121,7 +126,12 @@ public function read(string $sessionId): string
*/
public function write(string $sessionId, string $sessionData): bool
{
- $session = ['_id' => $sessionId] + unserialize($sessionData);
+ $data = @unserialize($sessionData, ['allowed_classes' => false]);
+ if (!is_array($data)) {
+ return false;
+ }
+
+ $session = ['_id' => $sessionId] + $data;
$options = ['upsert' => true];
$this->collection->replaceOne(['_id' => $sessionId], $session, $options);
$this->updateTimestamp($sessionId);
diff --git a/src/Handlers/RedisClusterSessionHandler.php b/src/Handlers/RedisClusterSessionHandler.php
index 43ef270..f19dcd8 100644
--- a/src/Handlers/RedisClusterSessionHandler.php
+++ b/src/Handlers/RedisClusterSessionHandler.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
diff --git a/src/Handlers/RedisSessionHandler.php b/src/Handlers/RedisSessionHandler.php
index bab780f..7705db5 100644
--- a/src/Handlers/RedisSessionHandler.php
+++ b/src/Handlers/RedisSessionHandler.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
diff --git a/src/Install.php b/src/Install.php
index 4d77dc4..eca94d9 100644
--- a/src/Install.php
+++ b/src/Install.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
diff --git a/src/functions.php b/src/functions.php
index 9994d97..136a874 100644
--- a/src/functions.php
+++ b/src/functions.php
@@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin
- * @copyright Copyright (c) 2023-2024 Triangle Framework Team
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
@@ -56,4 +56,4 @@ function session(mixed $key = null, mixed $default = null): mixed
}
return $session->get($key, $default);
}
-}
\ No newline at end of file
+}
diff --git a/tests/mongo-integration.php b/tests/mongo-integration.php
new file mode 100644
index 0000000..d81e94a
--- /dev/null
+++ b/tests/mongo-integration.php
@@ -0,0 +1,88 @@
+
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
+ * @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published
+ * by the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see .
+ *
+ * For any questions, please contact
+ */
+
+require_once dirname(__DIR__) . '/vendor/autoload.php';
+
+use MongoDB\Client;
+use Triangle\Session\Handlers\MongoSessionHandler;
+
+function expectMongoIntegration(bool $condition, string $message): void
+{
+ if (!$condition) {
+ throw new RuntimeException($message);
+ }
+}
+
+$uri = getenv('MONGODB_URI');
+if ($uri === false || $uri === '') {
+ throw new RuntimeException('MONGODB_URI must point to a MongoDB integration-test service.');
+}
+
+if (!extension_loaded('mongodb')) {
+ throw new RuntimeException('The mongodb PHP extension is required for this integration test.');
+}
+
+$databaseName = 'triangle_session_test_' . bin2hex(random_bytes(8));
+$collectionName = 'sessions';
+$sessionId = 'sessionmongo' . bin2hex(random_bytes(8));
+$client = new Client($uri, ['serverSelectionTimeoutMS' => 5000]);
+$collection = $client->selectCollection($databaseName, $collectionName);
+$handler = new MongoSessionHandler([
+ 'url' => $uri,
+ 'database' => $databaseName,
+ 'collection' => $collectionName,
+ 'options' => ['serverSelectionTimeoutMS' => 5000],
+]);
+
+try {
+ $payload = [
+ 'user_id' => 41,
+ 'preferences' => ['theme' => 'dark'],
+ ];
+
+ expectMongoIntegration($handler->open('', 'PHPSESSID'), 'Mongo session handler should open.');
+ expectMongoIntegration($handler->write($sessionId, serialize($payload)), 'Mongo session handler should write valid serialized arrays.');
+
+ $document = $collection->findOne(['_id' => $sessionId]);
+ expectMongoIntegration($document !== null, 'MongoDB should persist the session document.');
+ expectMongoIntegration($document->user_id === 41, 'MongoDB should preserve scalar session values.');
+ expectMongoIntegration($document->preferences->theme === 'dark', 'MongoDB should preserve nested session values.');
+ expectMongoIntegration($document->updated_at instanceof MongoDB\BSON\UTCDateTime, 'MongoDB should persist the update timestamp as BSON UTCDateTime.');
+
+ $restored = unserialize($handler->read($sessionId), ['allowed_classes' => false]);
+ expectMongoIntegration($restored === $payload, 'Mongo session data should survive a BSON write/read round trip.');
+
+ expectMongoIntegration(!$handler->write($sessionId, 'not a serialized array'), 'Malformed session payloads should be rejected.');
+ $unchanged = $collection->findOne(['_id' => $sessionId]);
+ expectMongoIntegration($unchanged->user_id === 41 && $unchanged->preferences->theme === 'dark', 'Rejected payloads must not overwrite stored session data.');
+
+ expectMongoIntegration($handler->destroy($sessionId), 'Mongo session handler should destroy a session.');
+ expectMongoIntegration($collection->findOne(['_id' => $sessionId]) === null, 'Destroyed sessions should be removed from MongoDB.');
+} finally {
+ $client->dropDatabase($databaseName);
+}
+
+echo "SESSION_MONGODB_INTEGRATION=ok\n";
diff --git a/tests/session-compatibility.php b/tests/session-compatibility.php
new file mode 100644
index 0000000..12a9fb1
--- /dev/null
+++ b/tests/session-compatibility.php
@@ -0,0 +1,148 @@
+
+ * @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
+ * SPDX-License-Identifier: AGPL-3.0-or-later
+ * @license AGPL-3.0-or-later
+ */
+
+namespace {
+ require_once dirname(__DIR__) . '/vendor/autoload.php';
+}
+
+namespace MongoDB {
+ if (!class_exists(Client::class)) {
+ class Client
+ {
+ }
+
+ define(__NAMESPACE__ . '\\SESSION_TEST_STUBS', true);
+ }
+
+ if (!class_exists(Collection::class)) {
+ class Collection
+ {
+ public static ?array $lastReplacement = null;
+ public static ?array $lastOptions = null;
+ public static mixed $lastDocument = null;
+
+ public function findOne(array $filter, array $options = []): mixed
+ {
+ self::$lastOptions = $options;
+ return self::$lastDocument;
+ }
+
+ public function replaceOne(array $filter, array $replacement, array $options = []): void
+ {
+ self::$lastReplacement = $replacement;
+ }
+
+ public function updateOne(array $filter, array $update): void
+ {
+ }
+ }
+ }
+}
+
+namespace MongoDB\BSON {
+ if (!class_exists(UTCDateTime::class)) {
+ class UTCDateTime
+ {
+ }
+ }
+}
+
+namespace {
+ use localzet\Server;
+ use localzet\Server\Protocols\Http\Session as ServerSession;
+ use localzet\Server\Protocols\Http\Session\SessionHandlerInterface;
+ use Triangle\Engine\BootstrapInterface;
+ use Triangle\Session\Bootstrap;
+ use Triangle\Session\Handlers\FileSessionHandler;
+ use Triangle\Session\Handlers\MongoSessionHandler;
+ use Triangle\Session\Handlers\RedisClusterSessionHandler;
+ use Triangle\Session\Handlers\RedisSessionHandler;
+
+ final class SessionCompatibilityProbe
+ {
+ public static bool $woken = false;
+
+ public function __wakeup(): void
+ {
+ self::$woken = true;
+ }
+ }
+
+ function expect(bool $condition, string $message): void
+ {
+ if (!$condition) {
+ throw new RuntimeException($message);
+ }
+ }
+
+ expect(is_subclass_of(Bootstrap::class, BootstrapInterface::class), 'Session bootstrap must implement the Engine bootstrap contract.');
+ Bootstrap::start(new Server());
+
+ foreach ([FileSessionHandler::class, MongoSessionHandler::class, RedisSessionHandler::class, RedisClusterSessionHandler::class] as $handlerClass) {
+ expect(is_subclass_of($handlerClass, SessionHandlerInterface::class), "$handlerClass must implement the Server session handler contract.");
+ }
+
+ $sessionId = 'sessioncompat1234567890';
+ $savePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'triangle-session-' . bin2hex(random_bytes(6));
+
+ try {
+ ServerSession::handlerClass(FileSessionHandler::class, ['save_path' => $savePath]);
+
+ $session = new ServerSession($sessionId);
+ $session->put(['user_id' => 41, 'preferences' => ['theme' => 'dark']]);
+ $session->save();
+
+ $restored = new ServerSession($sessionId);
+ expect($restored->get('user_id') === 41, 'Scalar session values must survive a storage round trip.');
+ expect($restored->get('preferences') === ['theme' => 'dark'], 'Nested session arrays must survive a storage round trip.');
+
+ SessionCompatibilityProbe::$woken = false;
+ ServerSession::handler()->write($sessionId, serialize(['payload' => new SessionCompatibilityProbe()]));
+
+ $untrusted = new ServerSession($sessionId);
+ expect(!SessionCompatibilityProbe::$woken, 'Session payload objects must not execute wakeup hooks when restored.');
+ expect($untrusted->get('payload') instanceof __PHP_Incomplete_Class, 'Objects in restored session data must remain incomplete values.');
+ } finally {
+ ServerSession::handler()->destroy($sessionId);
+ @rmdir($savePath);
+ }
+
+ if (defined('MongoDB\\SESSION_TEST_STUBS')) {
+ $reflection = new ReflectionClass(MongoSessionHandler::class);
+ $mongoHandler = $reflection->newInstanceWithoutConstructor();
+ $collection = new \MongoDB\Collection();
+
+ $property = $reflection->getProperty('collection');
+ $property->setAccessible(true);
+ $property->setValue($mongoHandler, $collection);
+
+ \MongoDB\Collection::$lastDocument = [
+ '_id' => $sessionId,
+ 'updated_at' => new \MongoDB\BSON\UTCDateTime(),
+ 'user_id' => 41,
+ 'preferences' => ['theme' => 'dark'],
+ ];
+ $storedData = unserialize($mongoHandler->read($sessionId), ['allowed_classes' => false]);
+ expect($storedData === ['user_id' => 41, 'preferences' => ['theme' => 'dark']], 'Mongo session reads must preserve nested arrays without storage metadata.');
+ expect(\MongoDB\Collection::$lastOptions['typeMap'] === ['root' => 'array', 'document' => 'array', 'array' => 'array'], 'Mongo session reads must restore BSON documents and arrays as PHP arrays.');
+
+ SessionCompatibilityProbe::$woken = false;
+ $validPayload = serialize(['name' => 'safe', 'payload' => new SessionCompatibilityProbe()]);
+ expect($mongoHandler->write($sessionId, $validPayload), 'Mongo session writes should accept serialized arrays.');
+ expect(!SessionCompatibilityProbe::$woken, 'Mongo session writes must not instantiate objects from serialized session data.');
+ expect(\MongoDB\Collection::$lastReplacement['payload'] instanceof __PHP_Incomplete_Class, 'Mongo session writes must preserve object payloads as incomplete values.');
+
+ $previousReplacement = \MongoDB\Collection::$lastReplacement;
+ expect(!$mongoHandler->write($sessionId, 'not a serialized array'), 'Malformed Mongo session payloads must be rejected.');
+ expect(\MongoDB\Collection::$lastReplacement === $previousReplacement, 'Rejected Mongo payloads must not mutate storage.');
+ }
+
+ echo "SESSION_ENGINE_COMPATIBILITY=ok\n";
+}