Todd Sundsted
Todd Sundsted
toddsundsted@epiktistes.com
Better dead than bored.
Introductionepiktistes.com/introduction
GitHubgithub.com/toddsundsted/ktistec
Pronounshe/him
🌎Sector 001
Todd Sundsted

I've been on the Fediverse since January 2017. I initially ran a single-user instance of Mastodon. In March 2020 I started to write Ktistec, my own implementation of an ActivityPub server in Crystal (a language with the ergonomics of Ruby but the speed of Go) because I wanted something more supportive of writing. This #introduction was written and published on Epiktistes, my Ktistec instance.

I'm an Engineer by training but now I run teams for companies in climate-tech.

I love #music, #sciencefiction and #fantasy literature (yes, I'm an R. A. Lafferty fan), attend fan conventions like #worldcon and #dragoncon, and do regular #weightlifting. I am also learning to play the #bagpipes, and I'm (re)learning #japanese.

Todd Sundsted
The Ktistec executable is now ~24.7% smaller and build times are 28% faster. I've been blogging about optimizations here, here, and here. This is the summary of the final outcome, with links to commi…

The Ktistec executable is now ~24.7% smaller and build times are 28% faster.

I've been blogging about optimizations here, here, and here. This is the summary of the final outcome, with links to commits for the curious. I have one more post planned with a summary of my thoughts.

Here's my approach. Use nm to dump the symbols in a release build executable and then look for things that seem redundant. The first change and associated post below is a great example of what I mean—my original implementation led to the specialization of the #== method for every pairwise combination of model classes even though the result of the comparison was just false.

This might seem like a strange approach if you come from a compiled language where you mostly write all of the code yourself or invoke generics explicitly, but Crystal takes your code and does that for you. And it's not always obvious up front (to me, at least) what the final cost will be.

I've include counts of the lines added/removed because the point of this whole post is to say if you measure first and then optimize, a small change can have a big impact.

Here are the changes:

  • Specialize model #==. (+7 -5)
    I talked about this here but didn't have the commit to link to. This change results in a large reduction in executable size on regular builds (~4.0%) and a small difference on release builds (~0.2%).
  • Remove conversion to Hash. (+2 -2)
    This commit eliminates specialization of methods like __for_internal_use_only that get passed both named tuples and hashes by going all in with named tuples. It also eliminates instantiations of the Hash generic type itself for these cases. Reduces executable size by ~2.2%.
  • Eliminate duplicate code in the executable. (+3 -3)
    This small change reduces the size of the executable by a further ~0.4% by eliminating redundant definitions of __for_internal_use_only entirely.
  • Make InstanceMethods instance methods. (+1 -5)
    This was a goofy design I picked up somewhere. It's unnecessary. Changing this saves ~0.2% on release build executable size.
  • Move the code for digging through JSON-LD. (+246 -281)
    It looks like a lot of lines of code changed here, but the large numbers are the result of moving code line-by-line from an included module to a utility class. Invoking these as methods on the utility class rather than as instance methods on each including class reduces the executable size by ~0.5%.
  • Use map from base ActivityPub model classes. (+10 -2)
    map is a class method defined on each ActivityPub base model class. Each definition maps JSON-LD to a hash that is used to instantiate the class. Class methods defined on a base class are available on subclasses, as well. Calling the method on the subclass results in a copy of the method. This change reduces the executable size by ~5.8%.
  • Move map into helper. (+104 -88)
    The map method does not depend on class/instance state. This change ensures that the mapping code is not duplicated even if a subclass's map method is accidentally again called. It looks like a lot of changes but this commit is mostly reorganization. It reduces executable size by ~0.4%.
  • Replace classes with aliases. (+62 -148)
    Implementing ActivityPub's vocabulary with discrete model classes is expensive because every model class comes with machinery for type-specific CRUD operations. Enumerate aliases on each base model class (e.g. a "Service" is an "Actor"). This change reduces executable size by ~16.9%.

I'm off to optimize some queries now...

#ktistec #crystallang

Todd Sundsted

After I release a new version of ktistec, I build the server commit-by-commit to see which commits increase the server executable size and build time the most. I do this because I’ve learned that small implementation details (inlined code, small methods, using blocks) can have large impacts on these numbers.

Here's the output:

Commit         Size          Time
======== ========== ======= ===== =======
248850b1   36426264          10.3
47268073   36425688  -0.00%  10.5  +1.60%
344de272   36425688  +0.00%  10.8  +3.24%
ef561f52   36425944  +0.00%  10.8  -0.08%
8ae2cbd4   36429128  +0.01%  10.8  -0.01%
3e425f3b   36429128  +0.00%  10.8  +0.22%
1487d903   36427704  -0.00%  11.0  +1.42%
935c9ceb   36427016  -0.00%  11.0  +0.14%
de37dc6a   36427016  +0.00%  10.9  -0.97%
a660a326   36427016  +0.00%  10.8  -1.12%
ff3d990e   36427016  +0.00%  10.8  +0.54%
5724a58d   36523192  +0.26%  11.0  +1.78%
7b5057d4   36523640  +0.00%  11.0  -0.44%
30ca6a3f   36541352  +0.05%  11.6  +5.73%
e2327eea   36671592  +0.36%  11.0  -5.36%
ad0d76eb   36671592  +0.00%  10.9  -0.48%
d388e74f   36671592  +0.00%  11.4  +4.59%
dacea7ad   36671592  +0.00%  11.0  -3.76%
03d5dfd8   36671592  +0.00%  10.8  -1.63%
79d9d89f   36671576  -0.00%  11.0  +1.82%
b65d292f   36792376  +0.33%  11.1  +0.95%
0ef53365   36808904  +0.04%  11.6  +4.88%
b3766e7b   36808904  +0.00%  11.1  -4.50%
56ba79ce   36825416  +0.04%  11.1  -0.50%
4824df58   36825736  +0.00%  11.1  +0.31%
c4705143   36837544  +0.03%  11.1  -0.03%
e3d37ef7   36837768  +0.00%  11.5  +3.52%
4509fa0d   36837768  +0.00%  11.0  -3.83%
0ff9237b   36837768  +0.00%  11.0  -0.55%

Overall, the server executable size increased by about 1.1% and the build time increased by about 6.8%. Maybe that's not too bad for a major feature, but let's dig in.

It's nice to see that three commits account for almost all of the increase in server executable size:

  • 5724a58d Add `language` to `Object`.
    2 files +19  loc
  • e2327eea Render `contentMap` on ActivityPub objects.
    2 files +17 -1 loc
  • b65d292f Add translation actions to the objects controller.
    1 file +35 loc

But, compare 5724a58d to 8ae2cbd4 (Add `language` to `Account`). It added +22 loc but didn't increase the server executable size as much.

In any case, I'll look at e2327eea first. I'd like to understand why this relatively small change adds 130,240 bytes to the server executable size!

The follow ups are here, here, here, and here.

#ktistec #crystallang

Todd Sundsted
Release v3.16.0 of Ktistec

The latest release ("walk the walk") of Ktistec completes the RFC 9421 work—the server now retries an outbound request with an RFC 9421 signature when its draft-cavage signature is rejected—and adds support for using private labels as feed criteria and replacing the default timeline with any published algorithmic feed.

I annotate posts with private labels to mark content I want to see (or don't want to see) and—now that I can use them as custom feed criteria—to group posts into topical reading lists, presented as feeds.

Being able to replace the default timeline with a custom feed is the closing chapter of a long-running desire of mine to separate the kind of posts I want to read (what people do) from the "hot takes" (what people say) that are part and parcel of social media 😀.

Here's the full changelog:

Added

  • Let a user choose a published feed as its timeline feed.
  • Retry rejected outbound requests with an RFC 9421 signature.
  • Add a link to Feeds in the top nav when on the deck.
  • Accept private labels as feed criteria.

Fixed

  • Restore the deck's scroll positions.
  • Map public keys from actor documents that omit the security context.
  • Decrement cached tag counts when a tag is destroyed.
  • Prefer alt text over figcaption in the image viewer's caption.

Changed

  • Put new feeds at the front of the deck.

I've shipped a lot of new features lately. The next few releases will focus on polishing them.

#ktistec #crystallang #activitypub #fediverse

Todd Sundsted
A test page showing the two cases: the original with icons fixed in place even when their labels shifted right; and the fix with both icons and labels shifted right.
Figure: The Test Page

Fixing this bug lost me some hair...

I have been living with a Ktistec rendering bug that shifts only the label in an icon/label pair when the page is morphed in response to a user gesture (e.g. liking a post), and then only in Safari on iOS.

Fixing it required setting both opacity: 1 and backface-visibility: visible. Apparently, the previous values caused the icon to be put into its own layer and Safari iOS doesn't repaint that layer when an in-place text change (a morph) shifts the icon.

#ktistec #safari #ios #bugsbugsbugs

Todd Sundsted
Algorithmic Feeds: The Data Exchange
The previous two posts (here and here) in this series on algorithmic feeds introduced the built-in criteria judge and external custom judges. A custom judge is a script run by the Ktistec server that…

The previous two posts (here and here) in this series on algorithmic feeds introduced the built-in criteria judge and external custom judges.

A custom judge is a script run by the Ktistec server that decides whether a post is included in the feed or excluded from the feed based on data about the posts that the server provides in a temporary SQLite database.

There is a lot of data to work with (the owner is you, the feed's creator):

  • feed
    One row describing the feed being judged.
    • name : The feed's name.
    • description : The feed's description.
    • params : The feed's parameters.
  • stats
    One row. Posts per day over the last 90 days, across the authors the owner follows (confirmed only, not deleted or blocked). Authors who posted nothing in that window are left out.
    • posting_rate_q1 : First quartile.
    • posting_rate_median : The median.
    • posting_rate_q3 : Third quartile.
  • authors
    One row per author of any post in posts or referenced. 
    • iri : The author's IRI.
    • type : The actor type.
    • handle : The author's handle.
    • followers : The IRI of the author's followers collection.
    • deleted : Whether the author is deleted.
    • blocked : Whether the author is blocked.
    • followed : Whether the owner follows the author (a confirmed follow).
    • rate_7, rate_30, rate_90 : The author's posts per day over the last 7, 30, and 90 days, counting only posts the server has cached that aren't deleted or blocked.
  • posts/referenced
    posts holds the posts to judge. referenced holds the posts replied to or quoted, one level deep. Both tables have the same columns.
    • iri : The post's IRI.
    • type : The object type.
    • name : The post's name (title).
    • summary : The post's summary (content warning).
    • content : The post's content as HTML (Markdown is converted).
    • language : The post's language.
    • sensitive : Whether the post is marked sensitive.
    • published : When the post was published.
    • to, cc, audience : The addressing, as arrays of IRIs.
    • attachments : An array of {url, media_type, caption}.
    • in_reply_to : The IRI of the post this one replies to.
    • quote : The IRI of the post this one quotes.
    • thread : The IRI of the thread's root.
    • hashtags, mentions : Arrays of {name, href}.
    • labels : An array of the owner's private labels on the post.
    • author : The author's IRI.
    • deleted : Whether the post is deleted.
    • blocked : Whether the post is blocked.
    • timeline : "create" or "announce" if the post is in the owner's timeline, otherwise NULL.
    • poll : {options, multiple_choice, closed_at}, but only when type is "Question".

This data is used in the example judges shipped with Ktistec.

The polls judge builds a feed consisting of polls. It includes only posts whose type is "Question". It would be very easy to extend this judge to filter on single-choice vs. multi-choice or on polls about specific topics.

The quiet_posters judge is a little more complex. The server provides statistics on all of the actors you follow, as well as the author's posts per day over the last 7, 30, and 90 days. A post is included only if you follow its author and that author's 90-day posting rate is at or below the median, so the quieter half of your follows aren't drowned out by the noisier ones.

As you might imagine, there's a lot of value in judges built around statistics, social signals, and interactions. This is the area where I'm now putting most of my effort.

#ktistec #AlgorithmicFeed #ActivityPub #fediverse

Todd Sundsted

crystal language version 1.22.3 has been released. it looks like there are a decent number of security-related fixes. great work getting those fixed and this released!

#crystallang

Todd SundstedWeek in Fediverse :fediverse_light:
Todd Sundsted

What’s the ideal split of refactoring time and effort vs. new development time and effort when adding a new feature?

4
3
0
0
Todd Sundsted
Algorithmic Feeds: A Custom Criteria Judge
In the last post in the series on algorithmic feeds in Ktistec, I introduced the built-in criteria judge, which renders verdicts on posts based on the presence or absence of terms, like hashtags and …

In the last post in the series on algorithmic feeds in Ktistec, I introduced the built-in criteria judge, which renders verdicts on posts based on the presence or absence of terms, like hashtags and keywords.

In this post, I introduce custom algorithmic feeds by showing you what a simple implementation of the criteria judge looks like if rewritten as a custom judge. Custom judges are nothing more than scripts, external to the server, that the server runs to judge candidate posts.

Here is the custom criteria judge:

#!/usr/bin/env python3
# ktistec: batch-size=250
# ktistec: param=any required
# ktistec: param=all
# ktistec: param=none
import html, json, re, sqlite3, sys
def terms(value):
    return [t.strip().lower() for t in (value or "").split(",") if t.strip()]
db = sqlite3.connect(sys.argv[1])
params = json.loads(db.execute("SELECT params FROM feed").fetchone()[0])
any_terms = terms(params.get("any"))
all_terms = terms(params.get("all"))
none_terms = terms(params.get("none"))
posts = db.execute("SELECT iri, name, summary, content, hashtags, mentions, labels FROM posts")
for iri, name, summary, content, hashtags, mentions, labels in posts.fetchall():
    text = " ".join(filter(None, (content, summary, name)))
    text = html.unescape(re.sub(r"<[^>]+>", " ", text)).lower()
    hashtags = {h["name"].lower() for h in json.loads(hashtags)}
    mentions = {m["name"].lower() for m in json.loads(mentions)}
    labels = {label.lower() for label in json.loads(labels)}
    def hit(term):
        if term.startswith("#"):
            return term[1:] in hashtags
        if term.startswith("@"):
            return term[1:] in mentions
        if term.startswith("§"):
            return term[1:] in labels
        return term in text
    included = not any(map(hit, none_terms)) and any(map(hit, any_terms)) and all(map(hit, all_terms))
    db.execute("INSERT INTO answers (iri, included) VALUES (?, ?)", (iri, int(included)))
db.commit()

It's simple, and it's not a perfect work-alike, but it shows the overall structure.

The Ktistec server runs judges, both built-in and custom, when there are candidate posts. Given a batch of posts, the judge makes exactly one decision: is each post included in the feed or excluded from the feed?

To do this, a judge is given the path to a temporary SQLite file (in sys.argv[1] in the example above) with information about the posts in the batch and their authors, as well as information about the feed itself.

Most of the time, posts arrive one at a time and the script runs on each post as it arrives. But the SQLite database can contain multiple posts—and it will when previewing or backfilling a feed—so the script must iterate over every post and judge each post independently.

In this example, the judge strips the post of markup and then looks for terms that match. It writes a verdict on the post into the answers table.

The front matter at the top of the file tells the server some things about the judge: the maximum batch size (the default is 1), and what params the judge expects the feed to provide. In this case, it expects three params, and the first is required. The params allow a user to create multiple, parameterized feeds from a single judge.

The params appear as inputs on the feed editor page.

A New Feed form with the Judge dropdown set to 'criteria-alike', above Name and Notes fields and three text inputs labeled Any (highlighted as required), All, and None. Create Feed, Preview Feed, and Cancel buttons are at the bottom.
Figure 1: Params as they are displayed in the feed editor

The "Judge" dropdown at the top of the form only appears when you create a feed, and only when there are custom judges. You make a script a custom judge by placing the script in the <root>/etc/judges directory, making it executable, and waiting a few minutes until the server picks it up, or restarting the server. Here the custom criteria judge was saved as <root>/etc/judges/criteria-alike.

The example is in Python, but you can use the language of your choice.

In the next post, I'll go over what else in the SQLite database supplied to the judge is useful for judging.

#ktistec #AlgorithmicFeed #ActivityPub #fediverse