feat(lib): add notebook cards and Nominal connection options #711
Claude finished @arsenovicAtNominal's task in 13m 29s —— View job
---
Code review
/code-review --comment over the diffOverview: The display layer is well-scoped — _repr_html_/_display_fields() builds cards purely from in-memory state (confirmed: no driver calls), and the new public attributes (client, stream_id, writer, closed, max_queue_size, …) are a sensible minimal surface rather than a new facade. NominalCorePublisher's three credential paths (client=/api_key/profile) are cleanly mutually exclusive via ValueError, consistent with the repo's explicit-over-abstracted style.
Posted 3 inline findings on instro/lib/publishers/nominal_core.py:
_credentials() (line 153) mislabels a directly-passed client= as "API key".close() (line 144) isn't idempotent, unlike BufferedPublisher.close() added in this same PR.profile/batch_size/max_wait default-fallback (lines 84, 91, 92) use x or default, which silently drops falsy-but-valid values like max_wait=timedelta(0).One process note (not inline, no single line to anchor it): the PR body itself calls out that Instrument(..., nominal_profile=...) / nominal_client=... used to be stored as a default tag and now configures the auto-created publisher (and raises ValueError without dataset_rid) — that's a documented breaking behavior change, but the PR title (feat(lib): ...) doesn't carry the ! Conventional Commits requires for it.
Test coverage looks solid elsewhere (credential conflicts, API-key redaction, link escaping, instrument-kwarg routing); no other convention or scope issues found.
<!-- greptile_summary -->
<h2><a href="https://app.greptile.com/api/retrigger?id=94761046"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img alt="Retrigger" src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2" align="right"></picture></a><a href="https://app.greptile.com/-/switch-tenant?tenant=nominal&next=%2Fnominal-io%2Finstro%2Fpull%2F711&utm_source=greptile_review&utm_medium=github&utm_campaign=view_in_greptile"><picture><source media="(prefers-color-scheme: dark)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source media="(prefers-color-scheme: light)" srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img alt="View in Greptile" src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2" align="right"></picture></a>Confidence Score: 4/5</h2>
[Medium impact] The changes affect notebook display and Nominal publishing for instro library users\.
The PR appears safe to merge with two non-blocking fixes recommended for credential labels and large-buffer reads.
<h2>Findings</h2>
1. <img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"> Credential source is mislabeled <a href="https://github.com/nominal-io/instro/pull/711#discussion_r4459396878">▶</a>
2. <img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"> Latest reads copy all history <a href="https://github.com/nominal-io/instro/pull/711#discussion_r4459396892">▶</a>
<details><summary>Fix with agent prompt</summary>
``### Issue 1
instro/lib/publishers/nominal_core.py:151-153
Passing a client created with `NominalClient.from_profile("staging")` makes the card and `repr()` say `API key`. The constructor sets `profile=None` for every supplied client, and `_credentials()` treats that as proof of API-key authentication. Track supplied clients separately and show “provided client” when their credential source is unknown.
### Issue 2
instro/lib/publishers/channel_buffer.py:192-193
`latest()` requests one sample through helpers that copy each entire deque before slicing it. For a `DequeInMemoryPublisher` with a large history, returning one value per channel copies all retained values and timestamps while holding the lock that publishing needs. Read the deque tails directly, or add a one-sample path that avoids those copies.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
</details>
<h3>Summary</h3>
Adds notebook cards, display options, public publisher state, and more ways to connect to Nominal.
<!-- greptile_confidence_score:4 -->
<sub>Reviews (1) · Last reviewed commit: "feat(lib): add notebook cards and Nomina..." · Reviewed by Greptile</sub>
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> Credential source is mislabeled
Passing a client created with NominalClient.from_profile("staging") makes the card and repr() say API key. The constructor sets profile=None for every supplied client, and _credentials() treats that as proof of API-key authentication. Track supplied clients separately and show “provided client” when their credential source is unknown.
<details><summary>Prompt To Fix With AI</summary>
``This is a comment left during a code review.
Path: instro/lib/publishers/nominal_core.py
Line: 151-153
Comment:
**Credential source is mislabeled**
Passing a client created with `NominalClient.from_profile("staging")` makes the card and `repr()` say `API key`. The constructor sets `profile=None` for every supplied client, and `_credentials()` treats that as proof of API-key authentication. Track supplied clients separately and show “provided client” when their credential source is unknown.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
</details>
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> Latest reads copy all history
latest() requests one sample through helpers that copy each entire deque before slicing it. For a DequeInMemoryPublisher with a large history, returning one value per channel copies all retained values and timestamps while holding the lock that publishing needs. Read the deque tails directly, or add a one-sample path that avoids those copies.
<details><summary>Prompt To Fix With AI</summary>
``This is a comment left during a code review.
Path: instro/lib/publishers/channel_buffer.py
Line: 192-193
Comment:
**Latest reads copy all history**
`latest()` requests one sample through helpers that copy each entire deque before slicing it. For a `DequeInMemoryPublisher` with a large history, returning one value per channel copies all retained values and timestamps while holding the lock that publishing needs. Read the deque tails directly, or add a one-sample path that avoids those copies.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
</details>
_credentials() can't distinguish a directly-passed client= from API-key auth: both end up with self.profile is None and self.client is not None, so NominalCorePublisher(dataset_rid, client=my_client) reports "API key" in the repr/card even though no API key was used (see test_client_fetches_the_dataset, which doesn't assert on _credentials()).
Fix this →%20at%20line%20148-153%20mislabels%20a%20directly-passed%20client%20as%20%22API%20key%22%20because%20self.profile%20is%20None%20and%20self.client%20is%20not%20None%20in%20both%20cases.%20Track%20whether%20the%20client%20was%20passed%20in%20directly%20(e.g.%20a%20new%20bool%20flag%20set%20in%20__init__)%20so%20_credentials()%20can%20report%20%22client%20passed%20directly%22%20instead.%20Branch%3A%20issue-709-notebook-cards&repo=nominal-io/instro)
close() doesn't check self.closed before calling self.write_stream.close(), so a repeat close (e.g. instrument.close() called twice) closes the Rust-backed stream twice. BufferedPublisher.close() added in this same PR (publisher.py:43-48) guards this with if self.closed: ... return — worth the same guard here.
Fix this →%20at%20line%20144-146%20calls%20self.write_stream.close()%20unconditionally%20even%20if%20self.closed%20is%20already%20True.%20Make%20it%20idempotent%20like%20BufferedPublisher.close()%20in%20instro%2Flib%2Fpublishers%2Fpublisher.py%20(around%20line%2043)%3A%20return%20early%20(optionally%20logging)%20if%20self.closed%20is%20already%20True.%20Branch%3A%20issue-709-notebook-cards&repo=nominal-io/instro)
max_wait or ws_signature.parameters["max_wait"].default treats timedelta(0) as falsy, so an explicit max_wait=timedelta(0) (immediate flush) is silently replaced by the API default. Same pattern on line 84 (profile or "default" promotes profile="") and line 91 (batch_size or default). Use is not None checks instead.
Fixed in 03804a0: the publisher now records whether a client was passed in, and _credentials() reports provided client for it (covered in test_client_fetches_the_dataset).
Fixed in 03804a0 together with the thread above: a directly passed client= now shows as provided client, and the test asserts it.
Fixed in 03804a0: DequeInMemoryPublisher (and the deque path of NumpyInMemoryPublisher) now read the last n items with islice(reversed(deque), n), so latest() copies one item per channel instead of the whole history while holding the lock.
Fixed in 03804a0: close() now returns early with a warning when already closed, matching BufferedPublisher.close(). Added test_close_is_idempotent.
Fixed in 03804a0 for batch_size, max_wait and file_fallback: they now use is not None, so max_wait=timedelta(0) is kept (new test). I left profile or "default" as is on purpose: _resolve_nominal_client also treats profile="" as "default" and loads that profile, so the label matches the credentials actually used.
This level of detail may be unnecessary; I'd cut the whole sentence, but especially the part about never showing the API key.
Is this rendered as a notebook already? If so, is it worth repeating the content of the card in words?
I couldn't confirm what this looks like, so added a PR for build previews.
It's not typical to recommend using internal functions in Python; should probably be instro.lib.set_display_options?
A custom {py:class}`~instro.lib.Instrument` subclass gets a default card automatically. To customize the card, override `_display_fields()` and return `(label, html)` pairs built from in-memory state only.
This could be clearer.
Between this and the above comment, I derive that _display_summary() is only for adding rows. What if you want to rewrite how a card looks?
It may be better to have the user be able to override _display_summary() entirely, and to use super().display_summary() where they only want to append?
Worth adding a field for this, vs interpreting dataset_rid as string | Dataset? Ideally would have used only dataset (which then also accepts rid), and deprecate dataset_id; is that too inconsistent with what's happening elsewhere?
Yes, this confirms my feeling that these are the same parameter :)
Maybe credential should also accept client | key | profile.
Overall looks good; just some quick API design questions.
Note to self: notebook running is added in https://github.com/nominal-io/instro/pull/713
Cut in 20797ec. The NominalCorePublisher card is now one sentence ("links its dataset in Nominal"), with no mention of the API key.
Not rendered in this PR; #713 adds the executed example notebook. Either way, I replaced the bullet list with one sentence in 20797ec, so the page doesn't repeat the card.
Done in 20797ec: the guide links instro.lib.set_display_options, and the reference page (docs/ref/library/display.md) now lists DisplayOptions and both functions under instro.lib instead of instro.lib._display.
Applied in 20797ec.
Agreed, overriding and calling super() is the model; the docs didn't say so. Clarified in 20797ec:
_display_fields() returns all the category rows, so InstroPSU's returns the channel count. A subclass that overrides it without super() drops those rows. The guide now shows [*super()._display_fields(), (label, html)]._repr_html_()._display_summary() is the one-line description of a publisher in an instrument's card, not rows. A subclass of a built-in publisher can extend it with super()._display_summary().I didn't add a default _display_summary to the Publisher Protocol, because that would make it a required member for mypy and break duck-typed publishers. Publishers without it still show their class name.
Done in 20797ec. The first argument is now dataset: str | Dataset, a RID or a fetched Dataset. Callers who pass the RID positionally don't change.
I kept dataset_rid= as a silent keyword alias rather than deprecating it in this PR. About 60 call sites use it (examples, docs, hardware tests, instro-unstable), and #724 rewrites many of the same example files. A DeprecationWarning would show on every example run as a script. Once #724 lands, I'd do the migration and the deprecation in a follow-up. Instrument(dataset_rid=...) and the JSON config key stay as they are, since they only ever take a RID.
I went a slightly different way in 20797ec. A single credential would have to tell a profile name from an API key, and both are strings. Instead, I dropped client= and base_url=, which this PR had added. A Dataset already carries its client's credentials, so any client is covered by NominalCorePublisher(client.get_dataset(rid)), including an API key with another base URL (documented in publishers.md). The remaining credential options are profile and api_key, the same as on main. Instrument(dataset_rid=..., nominal_client=...) now fetches the dataset with that client.
Small update since my last reply: as of 69b3f8c, PSU, scope and AWG no longer override _display_fields(). Their override was the same "Channel count" row three times, so the base card now reads _num_channels with getattr, the same way it already handles _driver. Built-in instruments have no _display_fields() override now, but the guide still recommends starting from super()._display_fields().
arsenovicAtNominal
Summary
First half of #709.
Notebook cards. Instruments and publishers display as HTML cards in Jupyter, VS Code and Colab, and have a one-line
repr.- the driver and channel count
- the background daemon's state, interval and last loop time
- each publisher, with an Open in Nominal link for a
NominalCorePublisher- the latest channel values once
start()has run- the default tags
set_display_options/get_display_options/DisplayOptionsare exported frominstro.liband follow nominal-client's options.instro/lib/_display.pyare copied from nominal-io/nominal-client#1260 and keep its CSS class names andrender/Sectionsignatures. Switching to a shared module is tracked in #710 and nominal-io/nominal-client#1263.Connecting to Nominal.
NominalCorePublisher's first argument isdataset: a RID or an already-fetchedDataset. ADatasetcarries its client's credentials, soNominalCorePublisher(client.get_dataset(rid))works with any client.dataset_rid=still works as a keyword alias. Credentials for a RID are stillprofileorapi_key; conflicting combinations raiseValueError.client,dataset,dataset_rid,profile,batch_size,max_wait,file_fallback,write_streamandclosedare public attributes. The API key isn't stored.Instrument(..., dataset_rid=..., nominal_profile=..., nominal_client=...): the two new keywords configure the auto-created publisher and are not default tags. Either one withoutdataset_ridraises.NominalCorePublisherentry in JSON config takesmax_wait_sandfile_fallback.Public publisher state.
NominalConnectPublisher:client,stream_id,sourceFilePublisher:writerBufferedPublisher:closedQueuedPublisher:max_queue_size,wait_for_queue,queue_sizeSharedPublisher:publisherChannelBufferPublisher: a newlatest()methodType of change
feat)Verification
just check-pythonpasses, and so doesuv run pytest testsexcepttests/ethernetip, which I couldn't run because the locally built EtherNet/IP extension fails to load on my machine (unrelated to this change).sphinx-build -E -W) passes.VirtualPSUcard with the daemon running and a queuedFilePublisherattached, and checked the fields, publishers, channels and tags in the HTML.Tests
-
tests/lib/test_display.py:- the instrument card makes no driver calls
- user values are escaped
- the latest values appear while the instrument runs
-
style="text"returns no card-
ChannelBufferPublisher.latest()-
tests/lib/test_nominal_core_publisher.py:- exactly one dataset, and the
dataset_rid=alias- the
Datasetpath- credential conflicts
- the API key never appears in
repr, the card orvars()- the dataset link, and no link when links are off or the URL can't be resolved
- the
Instrumentkeywords- The config tests now expect the two new
NominalCorePublisherarguments.Checklist
- new
docs/library/notebook-display.mdanddocs/sdk/library/display.md-
docs/library/publishers.mdanddocs/library/config-files.mdNotes for reviewers
nominal_profile=ornominal_client=to an instrument used to add a default tag. Now they configure the auto-createdNominalCorePublisher.🤖 Generated with Claude Code