Repository navigation
Conversation
…cording - Discover running Jupyter servers from their runtime files, or add one with trail.jupyter.connect(), and keep one websocket feed subscription per server with reconnects, backoff and a connection state - Resolve each feed message's map path to a tracked asset and record a JupyterEvent, skipping duplicate or unattributable messages with a reason - Factor the run lifecycle into a Session base; watchdog and Jupyter sessions share Trail's lock, and the console runs both and shows subscribed servers in its header - Event.apply() appends by default and Event.from_record() dispatches to the subclass, so JupyterEvent replays from the log - Add the PR draft, notes and demo notebook under ai/ and human/, moving notes/ into ai/plan, ai/report and ai/explain
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Note
🤖 This PR is AI-generated and human-reviewed, based on human-written notes.
Tip
📓
ai/examples/jupyter.ipynbdemonstrates this PR against a real Jupyter Server.This PR lets Trail record what users do in JupyterGIS. JupyterGIS posts events to Jupyter
Server, Jupyter Server broadcasts them on its event feed, and Trail subscribes to that feed and
records each message as an event on the map file's asset.
trail.jupyter.connect().JupyterEvent. Messages that cannot be attributed are skipped with a reason.WatchdogSessioninto aSessionbase. Watchdog and Jupyter sessions hold Trail's lock together.Event flow
An event travels from JupyterGIS to Trail's log as follows:
flowchart TD gis["JupyterGIS (browser)"] -- "POST /api/events" --> js["Jupyter Server"] js -. "writes at startup" .-> rt[("jpserver-*.json")] subgraph session ["trail.jupyter.session"] refresh["Servers.refresh()<br/>every 2 s"] sub["Server.subscribe()"] con["Consumer.text_to_message()"] msg["Message"] end rt -. "JSONs.refresh()" .-> refresh refresh -- "starts" --> sub js -- "/api/events/subscribe" --> sub sub -- "feed text" --> con con --> msg msg -- "_message_to_asset()" --> asset["Asset (.jGIS file)"] msg -- "JupyterEvent.apply()" --> events[("trail.events")] msg -- "kept" --> msgs[("session.messages")]Jupyter, reached astrail.jupyter, owns discovery and oneJupyterSession.Servers.refresh(). It rereads the runtime files throughJSONsand starts aServer.subscribe()task for each eligible server.Consumer, which wraps it in aMessage, resolves its map file, and records aJupyterEvent.Messagesfor debugging.Access map
Everything in this PR is reached from a
Trail. Solid arrows are attributes; dotted arrows are lookups by key:flowchart TD trail(["Trail"]) -- ".jupyter" --> jupyter(["Jupyter"]) trail -- ".events" --> events(["Events"]) jupyter -- ".jsons" --> jsons(["JSONs"]) jupyter -- ".manual" --> manual(["dict[str, JSON]"]) jupyter -- ".disconnected" --> disconnected(["set[str]"]) jupyter -- ".session" --> session(["JupyterSession"]) jsons -. "[path]" .-> json(["JSON"]) session -- ".servers" --> servers(["Servers"]) session -- ".consumer" --> consumer(["Consumer"]) session -- ".messages" --> messages(["Messages"]) servers -. "[url]" .-> server(["Server"]) messages -. "[id]" .-> message(["Message"]) events -. "[id]" .-> event(["JupyterEvent"])Entry point
Jupyteris reached throughTrail.jupyter, the only new attribute onTrail. Everything else in this PR is reached through it.Jupyter(Node)
Jupyterholds the Jupyter integration of one project: server discovery, manually added servers, and the current session. Its repr lists the servers of that session.trail.jupyter: JupytersessionJupyterSession.del trail.jupyter.sessioncloses it and creates a fresh onejsonsJSONs: the runtime files Trail discovers automaticallymanualdict[str, JSON]: servers added withconnect(), by URLdisconnectedset[str]: URLs closed bydisconnect(). Excluded from automatic reconnectionon_noticeon_messageMessageJupyter.connect(url=, token=, root=)adds a server Trail cannot discover, such as one in a container, tomanual.urlis the server's HTTP(S) base URL, such ashttp://localhost:8888/orhttp://localhost:8888/jupyter/.tokenis its authentication token, or an empty string.rootis the server's document root as Trail sees it. Feed messages name files relative to it. Discovery reads it fromroot_dirin the runtime file.Jupyter.disconnect(url)closes the server's feed and adds its URL todisconnected. The set lives onJupyter, not the session, so later refreshes and replacement sessions in the same process do not reconnect. It is not saved to disk.connect()removes the URL again.Jupyter.overlaps(root)decides whether a discovered server can name a tracked file. Servers that do not overlap stayavailableand are not subscribed.Jupyter.is_inside(folder)decides whether a new map file belongs to the project.on_noticeoron_messagecallback only warns.After a disconnect,
connect()reattaches the same server. The manual details differ from the runtime file's, so the server is replaced by a newServerwith the next number:trail.jupyter.manual: dict[str, JSON]Server discovery
Jupyter Server writes
jpserver-<pid>.jsonto its runtime directory at startup and removes it at shutdown.jupyter --pathslists that directory;JUPYTER_RUNTIME_DIRoverrides it.JSONholds the connection details of one server.Secrethides its token.JSONsreads the runtime files intoJSONinstances.JSON
JSONis a frozen dataclass of one server's connection details, from its runtime file or fromconnect().trail.jupyter.jsons[path]: JSONurlnormalize_url()and used as the server keyroottokenSecret. Excluded from the repr and from equalitypathNoneforconnect()pidmtimeis_password_protectedJSON.is_runningis alwaysTruefor a manually added server, even before a connection succeeds. For a discovered server it isFalseif the PID is invalid, the process has exited or is a zombie, or the PID was reused by a process started after the runtime file was written.normalize_url()adds the trailing slash and rejects a token query string,user:password@hostcredentials, non-HTTP schemes, and fragments.Secret
Secretholds a token. Its repr and string are<secret>, and pickling it raisesTypeError, so tokens cannot reach reprs, logs, or the event log.JSONs(Mapping[Path, JSON])
JSONsmaps runtime file paths to theirJSON.trail.jupyter.jsons: JSONsJSONs.refresh()is called byServers.refresh(). It globsjpserver-*.json, rereads a file only when its modification time or size changed, and drops entries for removed files.Note
🚧 Invalid runtime files and Unix-socket servers are skipped silently (todo).
Sessions
A session is a run that lasts from
start()toclose()orstop(). This PR adds a Jupyter session beside the filesystem one and moves their shared lifecycle into a base class.Session(Node)
Sessionis the base ofWatchdogSessionandJupyterSession. It suppliesasync with:__aenter__starts a run and__aexit__stops it.bool(session)says whether a run has started in this process and has not closed. A forked child does not inherit the run.is_activesays whether the run's tasks are alive.trail.lockwhen they start. Two sessions in one process share it; another process cannot record into the same project until both release it.WatchdogSession, withHandler,Access,Accesses,Watches, andArrival, moves fromtrail.sessiontotrail.watchdog.trail.sessionkeeps only the base class.JupyterSession(Session)
JupyterSessionis the run that discovers servers and listens to their feeds. It does nothing until started.trail.jupyter.session: JupyterSessionIn the notebook, the watchdog session started on the kernel's loop when the project opened, so both sessions hold the lock.
servers,consumer, andmessages.JupyterSession.start()needs a running asyncio loop and Trail's lock. It stores ataskrunningrun(), which callsServers.refresh()everyintervalseconds, 2 by default.JupyterSession.close()cancels the task, marks each serverstopped, and releases the session's hold on the lock without waiting.JupyterSession.stop()closes the session and waits for the discovery task and each server's subscription task.The notebook stops the session at the end:
Servers and subscriptions
Serversholds the servers of one session and decides which to subscribe to.Serverholds one subscription, its state, and its message counts.Servers(Mapping[str, Server])
Serversmaps normalized server URLs toServerinstances. Lookup normalizes the key, soservers['http://127.0.0.1:43913']also works.trail.jupyter.session.servers: ServersServers.refresh()reconciles the servers with the runtime files andJupyter.manual:stopped.Serverwith a new one and a new number. The old one is markedstopped.Jupyter.disconnected, has a token when password-protected, and overlaps the project or was added withconnect().Server
Serveris one Jupyter server and the state of its feed subscription.trail.jupyter.session.servers[url]: ServerserversServersthat holds itnumberjsonJSONit was found withstateStatebelowlast_errorcountsCountsof messages received, recorded, skipped byReason, andotherby schema for schemas Trail does not handlesubjectstasksubscribe()backoff,ceilingConnection states
availableconnectingsubscribedretryingrefusedunsupportederrordisconnecteddisconnect()stoppedA server moves between these states as follows. The dashed states end the subscription task:
refused,unsupportedanderror; the server stays in that state until it is disconnected, its runtime file goes away, or changed connection details makeServers.refresh()replace it with a newServer.flowchart TD available([available]) connecting([connecting]) subscribed([subscribed]) retrying([retrying]) refused([refused]) unsupported([unsupported]) error([error]) any(["any state"]) disconnected([disconnected]) stopped([stopped]) available -- "eligible, session active" --> connecting connecting -- "websocket open" --> subscribed subscribed -- "connection closed" --> retrying retrying -- "after backoff" --> connecting connecting -- "connection failed" --> retrying connecting -- "401/403, redirect, TLS" ---> refused connecting -- "404" ---> unsupported connecting -- "unexpected error" ---> error any -- "disconnect()" --> disconnected any -- "process gone, session ends" --> stopped stopped -- "session restarts" --> connecting classDef dead stroke-dasharray: 5 4 class refused,unsupported,error deadFeed subscription
Server.subscribe()is the task started byServers.refresh():POST /api/events./api/events/subscribe.subscribe()connects to that websocket with Tornado'swebsocket_connect, sending the token in anAuthorizationheader, never in the URL.session.consumer.text_to_message(). A consumer error is counted and does not end the feed.ceiling.The server remembers which asset each subject's map resolved to, so later messages from that view follow the same asset after a rename:
trail.jupyter.session.servers[url].subjects: dict[str, Asset]Server.locate()resolves a feed path below the server root. Absolute paths,.., backslashes, drive letters, and null bytes returnNone.Server.close()closes the socket, cancels the task, and sets the state.Messages and events
Consumerturns feed text into messages and events.Messagerecords one message and what became of it.Messageskeeps the latest messages.JupyterEventis the recorded event.Consumer(Node)
Consumerinterprets feed messages for one session. It numbers arrivals and remembers recorded deliveries.trail.jupyter.session.consumer: ConsumerJupyter Server sends each event to subscribers as one line of JSON text. It is the
dataJupyterGIS posted, withschema_idadded at the top level. Jupyter Server adds no envelope or timestamp, soMessage.timestampis Trail's arrival time. This is the raw feed text for the notebook's first event, read from a second subscription opened withserver.endpointandserver.headers():Indented for reading:
{ "schema_id": "https://schema.jupytergis.org/events/document/v1", "subject": "client-1", "verb": "opened", "object": { "document_path": "map.jGIS" } }Consumer.text_to_message(server, text)handles one message:schema_id. Invalid text is counted asinvalid message; a schema outsidehttps://schema.jupytergis.org/events/is counted undercounts.other.Messageand pass it to_record_message(). A malformed payload is skipped asinvalid payload.session.messagesand pass it toon_message, unless it was skipped asunsaved,outside root, oroutside project.Consumer._record_message()records a message:verb,object,object.document_path, andsubject, then resolves the asset with_message_to_asset(). It returns early if the message was skipped.streamandseqis a delivery. A repeat of the same server URL, stream, and sequence number is skipped asduplicate delivery; only the first is recorded. The last 10,000 deliveries are remembered.JupyterEvent.registryby schema. An unregistered schema records the baseJupyterEvent.Event.apply()appends the event totrail.events. The message keeps the event, andcounts.recordedincreases.Consumer._message_to_asset()returns the tracked asset of the message's.jGISfile, orNone. It writes the file's absolute path tomessage.src_path:server.subjects, even if the file was renamed._moved(), newest first.Message checks
The checks run in this order: a message that passes a check continues down, and one that fails leaves to the right. Dashed outcomes are counted on the server but not kept in
session.messages; the others are kept with their reason.flowchart TD text["feed text"] text --> parse["JSON object with schema_id?"] parse -- yes --> prefix["JupyterGIS schema?"] parse -- no --> invalid["invalid message"] prefix -- yes --> payload["verb, object and document_path valid?"] prefix -- no --> other["counts.other"] payload -- yes --> saved["map saved to a file?"] payload -- no --> badpayload["invalid payload"] saved -- yes --> root["inside the server root?"] saved -- no --> unsaved["unsaved"] root -- yes --> resolve["resolve the asset: server.subjects,<br/>logged moves, tracked path"] root -- no --> outroot["outside root"] resolve --> off["not offtrailed, ignored<br/>or Trail metadata?"] off -- yes --> project["tracked, or in a project folder?"] off -- no --> offtrailed["offtrailed"] project -- yes --> exists["file exists?"] project -- no --> outproject["outside project"] exists -- yes --> track["track the map if new"] exists -- no --> missing["file missing"] track --> dup["delivery not recorded yet?"] dup -- yes --> record(["JupyterEvent.apply(): recorded"]) dup -- no --> duplicate["duplicate delivery"] invalid ~~~ other other ~~~ badpayload badpayload ~~~ unsaved unsaved ~~~ outroot outroot ~~~ offtrailed offtrailed ~~~ outproject outproject ~~~ missing missing ~~~ duplicate classDef dropped stroke-dasharray: 5 4 class invalid,other,unsaved,outroot,outproject droppedIf the file cannot be used, the message is skipped with a
Reason:invalid messageinvalid payloadunsavedoutside rootoutside projectofftrailedfile missingduplicate deliveryconsumer errorThe notebook's unsaved map is counted on the server but not kept:
Message
Messageis one feed message and its outcome. The payload is excluded from the repr.trail.jupyter.session.messages[id]: MessagenumbertimestampserverschemadataidMessagessrc_pathoutcomeOutcome:pending,recorded, orskippedreasonReasonit was skipped, or emptyeventMessage.skip(reason)setsoutcometoskippedand records the reason.Messages(Collection[str, Message])
Messageskeeps the latest messages for debugging. It is in memory only.trail.jupyter.session.messages: Messageslimitmessages, 1000 by default, dropping the oldest. Arrival numbers are unchanged when older messages drop.messages.select('outcome=skipped')andmessages.select[-1].JupyterEvent(Event)
JupyterEventis an event reported by a Jupyter server's feed. Itsentryis the map's asset.trail.events[id]: JupyterEventschemaanddatahold the schema ID and a copy of the payload. Dictionary keys in the payload are interned.JupyterEvent.verbreads the payload's verb and is selectable, as inevents cls=JupyterEvent verb=opened.JupyterEvent.registry.__init_subclass__rejects a second class for the same schema.src_pathholds the resolved filesystem path;datakeeps the path JupyterGIS emitted. Nested payload fields are selectable with dotted names, sodata.object.document_path=map.jGISandentry.path=map.jGISselect the same event.Note
🧩 This PR registers no
JupyterEventsubclasses, so every message is recorded as the baseJupyterEvent. Later PRs add the JupyterGIS event classes.Changes to existing classes
Event.apply()now appends the event and returns its entry by default instead of raisingNotImplementedError.JupyterEventuses this default.Event.from_record()dispatches to the named class's ownfrom_record, so subclasses can restore their fields.Trail.jupytercreates theJupyterinstance on first access.Runrunstrail.watchdog.sessionandtrail.jupyter.sessiontogether and prints Jupyter notices as warnings.Renderer.header()addsjupyter subscribed/expectedwhile the session is active.Renderer.verb()uses aJupyterEvent's verb as its heading.Tests
The test fixtures build a project tracking
*.jgiswith onemap.jGIS, and aServerrooted at the project. An autouse fixture intests/conftest.pypointsJUPYTER_RUNTIME_DIRat a temporary folder, so tests never see real servers. Each linked phrase below opens its test.Discovery and servers
tests/jupyter/test_servers.pycovers runtime files, server replacement, and URL handling:{is skipped, and a removed file drops its entry.sockset to/tmp/jupyter.sockis skipped and is discovered oncesockis'', the value Jupyter writes. The password flag is read. This test fails if Unix-socket support is added.stopped, andis_stoppedafter its file is deleted.Server. The old one isstopped, and the new token is in theAuthorizationheader but not in the repr or endpoint.overlapsandis_insideaccept the project, its parent, and nested folders as appropriate.is_insideimpliesoverlaps.Secretandnormalize_url: the token is hidden and cannot be pickled, and URLs with a token query, credentials,ftp://, or a fragment are rejected.Sessions and the lock
tests/jupyter/test_lock.py:Trailon the same project cannot start either session, and the lock is released only after both stop.Subscription
The subscription test runs a Tornado
HTTPServerwith a fake/base/api/events/subscribefeed that checks the token and sends one map message on each connection. It runs twice:invalid messageand the next valid one is recorded.disconnect()leaves the serverdisconnected. Reopening the project replays three events, and the token is in neither the request URLs nor the log.refusedwithout retrying.Consumer
tests/jupyter/test_consumer.pycovers path resolution and skipping:opened map.jGISmessages, four are recorded. Another view's stream and messages without a stream are recorded.other.jGISunder a home-directory server root is skipped asoutside projectonce the project is narrowed to a subfolder.file missing, and an offtrailed map and a.hidden.jGISexcluded by.offtrailasofftrailed.AddAssetEventbefore its Jupyter event.map.jGISmoves tofirst.jGISand thensecond.jGIS, the old path follows the latest logged move tosecond.jGIS. A path with no logged move isfile missing.other), and anobjectthat is a list (invalid payload) are skipped, and the next valid message is recorded.Messages.limit, the oldest messages drop and arrival numbers stay.Events
tests/jupyter/test_events.pycovers recording and replay:untracked.txtreplays as a baseJupyterEventwith no asset.data.object.new.parameters.opacity<0.5.event.entryistrail.assets[event.entry.id]after reopening.Event.classes, or a second class for the same schema inJupyterEvent.registry, raisesTypeError.data.object.document_path=map.jGISandentry.path=map.jGIS.Ruff configuration
pyproject.tomlsetsallow-dict-calls-with-keyword-arguments = trueunder[tool.ruff.lint.flake8-comprehensions]. Ruff ruleC408no longer flagsdict(key=value)calls, such as thefieldsdict inConsumer. It still flagsdict()anddict([...]).